模拟私有实例变量的唯一方法是将它们声明为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.rules
需要从 Person 继承时复制到 Child 实例。
更多关于原型,继承,覆盖,调用超级,多重继承(混合)和this
这里的价值:https ://stackoverflow.com/a/16063711/1641941