I'm trying to create a class like architecture on javascript but stuck on a point. Here is the code:
var make = function(args) {
var priv = args.priv,
cons = args.cons,
pub = args.pub;
return function(consParams) {
var priv = priv,
cons = args.cons;
cons.prototype.constructor = cons;
cons.prototype = $.extend({}, pub);
if (!$.isFunction(cons)) {
throw new Hata(100001);
}
return new cons(consParams);
}
};
I'm trying to add the priv variable on the returned function objects's scope and object scope of the cons.prototype but I could not make it;
Here is the usage of the make object:
var myClass = make({
cons: function() {
alert(this.acik);
alert(priv.gizli);
},
pub: {
acik: 'acik'
},
priv: {
gizli: 'gizli'
}
})
myObj = myClass();
PS: Well I have used the outer vars for just to demonstrate what I want to do. I know the private variable syntax of javascript function structure. But I need a solutution for changing (adding private vars) the scope of a function which is going to be used by a "new" (i forgot the pattern name) instantiation pattern.
PS: Please forgive my english...
If your trying to replicate a class like structure the common approach in Javascript is as follows:
Note that within the functions you add to the prototype this will be a reference to the MyClass instance. If you would like to make private variables you can checkout this link from Javascript Expert Douglas Crockford: http://javascript.crockford.com/private.html
If you're after the class structure you really should follow the pattern of:
Important Note: When ever you set your var names of the inner closure to the same name as it's containing outer closure you no longer have access to the original outer closures vars with the same name.
On the other hand, if you need to access the outer closures vars there is no need to set the inner closures vars with the same name. Just work with the vars as if they're with-in the inner closure.
// If you need to add a var or private variable to a function object with the name cons: as you've got it below just add it like any other function object.