2

我有一个 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”。

有人有想法吗?

4

2 回答 2

3
this.__proto__.init(options);

将调用init原型上的方法,原型本身为this,导致您修改原型。尝试

this.__proto__.init.apply(this, [options]);

编辑

为避免__proto__您可以在隐藏它之前保存对原型初始化函数的引用:

Employee = function(options){
  this.Sal;
  var protoInit = this.init;
  this.init = function(options){
    this.Sal=options.Sal;
    protoInit.apply(this, [options]);
  }
  this.init(options);
}
于 2012-07-17T16:23:53.607 回答
2

init在错误的范围内调用。尝试这样的事情。

function Person(opt) {
    this.name = opt.name;
    this.id = opt.id;
}

function Employee(opt) {
    Person.call(this, opt);
    this.sal = opt.sal;
}

Employee.prototype = Object.create(Person.prototype, {});

您现在可以设置 和 的属性,Person.prototype它们的Employee.prototype行为应该符合预期。

这避免了使用 hacky 已弃用的属性 ( __proto__) 并且应该更清晰。Object.create用于使用超级构造函数的原型创建实例,而无需实际调用超级构造函数(无需init调用)。您可以包含半标准的属性定义,例如superconstructor您执行此操作时,正如许多库的inherits实现所做的那样。

于 2012-07-17T16:28:38.777 回答