我是JavaScript新手,我正试图用私有数据和公共函数创建“类”。有人告诉我立即调用函数表达式(IIFE)完成了这一任务,但是当我从类中“实例化”新对象时,它们引用私有数据而不是保存它们自己的数据。
其中一些是从Create a JS class: IIFE vs return prototype借来的。
例如,一个简单的汽车“类”:
var Car = (function() {
var body = { color: 'red' };
Car.prototype.newColor = function(color) {
body.color = color;
};
Car.prototype.getColor = function() {
return body.color;
};
return Car;
})();
var car1 = new Car();
var car2 = new Car();二氧化碳的颜色也会变成紫色。
car1.newColor('purple');
car2.getColor(); // 'purple'我希望Car类的每个对象都保存自己的私有数据。如何用IFFE实现这一点,或者还有其他方法?
发布于 2013-11-09 17:10:08
模拟私有实例变量的唯一方法是在构造函数中将它们声明为var myprivate。
任何特权方法(=可以访问私有成员的方法)也必须在构造函数的主体中声明,因此不能在原型上(将花费额外的cpu和内存,并且可能不会在某些JS引擎中进行优化)。
我从来没有遇到过需要这样做的情况,因为在我看来,付出的代价是不值得的。通常向我未来的自己和其他程序员指出,成员是私有的,使用广泛的命名约定(名称以下划线开头) _myPrivate
“公共覆盖”的回答激励我创建以下代码。私有实例成员可以由ben._data.set公开访问,或者您可以重新实现规则和或getter/setter,这样仍然可以有人滥用它。它仍然可以清除对象的可公开访问的成员,使使用getter和setter更容易。
//Namespacing DataStore to limit scope of the closures
var tools = {
DataStore : function(){
var store = [];
this.get = function(key){
return store[key];
};
this.set = function(key,value){
store[key] = value;
return value;
};
}
};
//Person constructor
var Person = function(name){
//you can access this member directly
// bob.name = "Lucy";
this.name=name;
//if having _data as not accesable by defining
// with var _data we whould have to define
// get and set here as this.get and this.set
this._data=new tools.DataStore();
};
//constant value used to get or set, for example:
//ben.get(ben.AGE);
//Could add this and rules to Person instead of Person.prototype
//then you'll need a helper function to set up inheritance
//to make sure the static's on Person are copied to it's children
Person.prototype.AGE=0;
//rules for getters and setters
//Will be a problem with inheritance if on prototype
//function Employee(name){Person.call(this,name);};
//Employee.prototype=Object.create(Person.prototype);
//Employee.prototype.rules["0set"]=..overwrites Person.prototype.rules["0set"]
//When inheriting you need to have a helper function set the rules for a child
//object
Person.rules = {}
//rule for AGE set
Person.rules[Person.prototype.AGE+"set"] = function(val){
var tmp;
tmp = parseInt(val);
if(isNaN(tmp)){
throw new Error("Cannot set the age of the person "+
"to non number value, value of age:"+val);
}
if(tmp>150){
throw new Error("Are you sure this is a person and "+
"not a turtule? Trying to set age to:"+val);
}
return this._data.set(this.AGE,tmp);
};
//rule for age get
Person.rules[Person.prototype.AGE+"get"] = function(){
return this._data.get(this.AGE);
};
Person.prototype.get = function(key){
return Person.rules[key+"get"].call(this);
};
Person.prototype.set = function(key,value){
return Person.rules[key+"set"].call(this,value);
};
var ben = new Person("Ben");
ben.set(ben.AGE,22);
console.log(ben.get(ben.AGE));
try{
ben.set(ben.AGE,151);
}catch(e){
console.log("error",e);
}
try{
ben.set(ben.AGE,"HELLO WORLD!");
}catch(e){
console.log("error",e);
}注意:当您想要从Person继承时,需要将Person.rules复制到子实例。
更多关于原型、继承、重写、调用超级继承、多重继承(混合)和this值的信息:https://stackoverflow.com/a/16063711/1641941
发布于 2013-11-09 18:07:08
但通过这种方式,每次创建对象时都要定义.privilegedMethod(),并且每个对象都包含不同版本的(相同用途)方法.
我提出的解决方案是使用object to object (私有) hashmap,并将新创建的对象映射到ctor函数中的相应数据,并使用hasmap作为“管理器”,在原型方法中找出哪些数据对应于哪个对象,如下所示:
var Car =
( function ( hashmap ) {
function PrivateClassCarData ( c, t ) {
this.color = c;
this.type = t;
}
function Car ( color, type ) {
hashmap.place( this, new PrivateClassCarData( color, type ) );
}
// read
Car.prototype.getColor =
function () {
return hashmap.read( this ).color;
};
// write
Car.prototype.setColor =
function (c) {
hashmap.read( this ).color = c;
return this;
};
// weak point, memory leak source
// dereference object from hash-map before updating variable that points to it
// another reference is kept in hashmap
// @TODO, automatic dereferencing execution, anybody?
Car.prototype.mfree =
function () {
hashmap.drop( this );
return this;
};
return Car;
} )(
// basic hash-map implementation
// maps objects to objects
( function ( hk, hv ) {
return {
place : function ( objKey, objVal ) {
hk.push( objKey );
hv.push( objVal );
return this;
},
read : function ( objKey ) {
return hv[ hk.indexOf( objKey ) ];
},
drop : function ( objKey ) {
var pos;
( ( pos = hk.indexOf( objKey ) ) != -1 )
&& (
hk.splice( pos, 1 ),
hv.splice( pos, 1 )
);
return this;
}
};
} )( [], [] )
);
var c1 = new Car("red","ferrary");
var c2 = new Car("white","porche");
c1.getColor();
// red
c2.setColor("silver");
c1.getColor();
// red
c2.getColor();
// silver
//发布于 2013-11-09 19:19:58
var Car =
( function ( cardb ) {
function Car ( color ) {
// facing the same problem here
// reinstaling .data() method for each created object
// but this way each has its own data store object
// and inner 1 to 1 circular reference js is able to deal with
cardb( this );
// set provided color parameter
this.data("color", color);
}
return Car;
} )(
// function to install .data() method to given object
// it gets attached to object directly, instead of
// attaching it to .prototype, in which case all
// object will access same data store
function ( obj ) {
var _data = {};
obj.data =
function ( name, value ) {
return arguments.length
? (
( value == null )
? _data[name]
: (
_data[name] = value,
this
)
)
: _data;
};
return obj;
}
);
var c1 = new Car("red");
var c2 = new Car("blue");
c1.data("color");
// red
c2.data("color");
// blue
c1.data("color","white");
c2.data("color");
// blue
c1.data("color");
// white
//https://stackoverflow.com/questions/19878346
复制相似问题