JS中的继承:this.base = Class(); this.base()还是......?

Mer*_*erc 7 javascript inheritance

我试图在JS中"获得"继承.我刚刚发现了一种简洁的方法,可以将所有属性从一个对象复制到另一个对象:

function Person(name){
  this.name="Mr or Miss: "+name;

  this.introduce = function(){
    console.log("Hi, I am "+this.name);
  }
}

function Employee(name,title){
  this.title=title;

  this.base=Person;
  this.base(name);  

}

e = new Employee('tony', 'manager')
e.introduce();
Run Code Online (Sandbox Code Playgroud)

请注意,我有一个带有构造函数的Person()类,其属性"name"由构造函数生成.关于这一点的好处还在于,员工在构造函数中也有名称 - 而且瞧,它使用相同的参数创建Person对象.

如果我用"原型"方式做到这一点:

function Person(name){

  this.introduce = function(){
    console.log("Hi, I am "+this.name);
  }
}

function Employee(name, title){
  this.name = name; /*  ?!?!?!?!? I can't call the proper constructor here */
  this.title = title;
}
Employee.prototype= new Person(); /* ?!?!? NO NAME HERE..>? */
Employee.prototype.constructor = Employee;


e = new Employee('tony', 'manager')
e.introduce();
Run Code Online (Sandbox Code Playgroud)

呃....现在怎么样?我甚至无法完成此操作:无法使用正确的Person构造函数设置Employee中的this.name; Person对象的创建只在继承中发生一次.

那么......我错过了什么?第一个例子我给出的"方式"是我的情况吗?有没有办法在第二个例子中得到相同的结果?

救命!

Fel*_*ing 12

这种原型继承通常以这种方式完成:

function Parent() {}

function Child() {
    Parent.call(this); // call the constructor of the parent
}

var Constr = function() {};
Constr.prototype = Parent.prototype;

Child.prototype = new Constr();
Child.prototype.constructor = Child;
Run Code Online (Sandbox Code Playgroud)

因此,"技巧"是将Parent.prototype原型分配给空函数,并将此函数的新实例设置为原型Child.

这样做是为了延长Child.prototype不延伸Parent.prototype.

您还必须在子的构造函数中调用父级的构造函数.我想这是你努力奋斗的部分.每个函数都有一个call [docs]apply [docs]方法,让你明确设置元素this应引用函数内部.

在您的示例中,它看起来像:

function Employee(name,title){
  this.title=title;

  Person.call(this, name);
}
Run Code Online (Sandbox Code Playgroud)

不将构造函数分配给实例的属性.

在你的例子中,this.base(name)工作,因为通过将构造函数分配给实例的属性(并以这种方式调用),this函数内部引用该实例.


有几个库实现了这种模式,例如Google Closure库:

goog.inherits = function(childCtor, parentCtor) {
  /** @constructor */
  function tempCtor() {};
  tempCtor.prototype = parentCtor.prototype;
  childCtor.superClass_ = parentCtor.prototype;
  childCtor.prototype = new tempCtor();
  childCtor.prototype.constructor = childCtor;
}; 
Run Code Online (Sandbox Code Playgroud)