I can define private member fields in module pattern using the code below
var myClass = function(){
var private_field1,private_field_2;
var private_func1 = function(){
//.......
}
//.........
var myObj = {
global_field1:2,
global_field2:"something",
global_func: function(){//......}
}
return myObj;
};
var obj = myClass();
This method works just fine, but the problem with this problem is that whenever I create a new object the copy of all the functions is created and loaded in memory (not like java where all objects of same class share same function memory)
I tried to use other method below:
var myClass = (function(){
var private_field1,private_field_2;//private static fields
var private_func1 = function(){
//.......
}
//.........
var Constr = function(){
//do something
}
Constr.prototype = {
//................
global_func: function(){//......}
}
return Constr;
}());
var obj1 = new myClass();
var obj2 = new myClass();
But the problem with this method is that obviously obj1,obj2 share same copy of private fields(so effectively they are static). So is there a way to define private fields in module pattern while using same copy of functions for the objects?
And for inheritance for the first method mentioned above, i first need to create a object inside the child class and then return that object.
var ChildClass = function(){
var childobj = myClass();
//override or add functions to childobj
return childobj ;
}
But this is effectively just wrapping the object of baseClass in childClass, Is there some other way to implement the same(for 1st or 2nd method) so that it can act like true java inheritance with protected, private, etc methods?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…