我有一个 Pers(on) 和一个从 Pers 派生的 Employee。
Pers = function(options){
this.Name;
this.ID;
this.init = function(options){
this.Name=options.Name;
this.ID=options.ID;
}
}
Employee = function(options){
this.Sal;
this.init = function(options){
this.Sal=options.Sal;
this.__proto__.init(options);
}
this.init(options);
}
Employee.prototype=new Pers();
现在当我创建新对象时...
var o=new Employee({Name:"Nik",ID:"1",Sal:100});
var p=new Employee({Name:"Tanja",ID:"2",Sal:200});
并提醒他们的名字,我会得到两次“Tanja”。
有人有想法吗?
最佳答案
this.__proto__.init(options);
将调用原型(prototype)上的init
方法,原型(prototype)本身为this
,导致您修改原型(prototype)。尝试一下
this.__proto__.init.apply(this, [options]);
编辑
为了避免 __proto__
,您可以在隐藏原型(prototype) init 函数之前保存对它的引用:
Employee = function(options){
this.Sal;
var protoInit = this.init;
this.init = function(options){
this.Sal=options.Sal;
protoInit.apply(this, [options]);
}
this.init(options);
}
关于使用原型(prototype)时 JavaScript 对象会被覆盖,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11526560/