Javascript调用Child中的父构造函数(prototypical inheritance) - 它是如何工作的?

时间:2014-11-19 13:27:09

标签: javascript constructor prototype call chain

我知道它有效,但我不知道为什么以及如何。有什么机制?

// Parent constructor
function Parent(name){
  this.name = name || "The name property is empty";
}

// Child constructor
function Child(name){
  this.name = name;
}

// Originaly, the Child "inherit" everything from the Parent, also the name property, but in this case
// I shadowing that with the name property in the Child constructor.
Child.prototype = new Parent();

// I want to this: if I dont set a name, please inherit "The name property is empty" from the 
// Parent constructor. But I know, it doesn't work because I shadow it in the Child.
var child1 = new Child("Laura");
var child2 = new Child();

//And the result is undefined (of course) 
console.log(child1.name, child2.name);  //"Laura", undefined

我知道我需要什么,call()apply()方法。从Parent调用“ super class ”(Child构造函数),并将this对象和参数name传递给它。它有效:

function Parent(name){
  this.name = name || "The name property is empty";
}

function Child(name){
  // Call the "super class" but WHAT AM I DO? How does it work? I don't understand the process, I lost the line.
  Parent.call(this, name);
}

Child.prototype = new Parent();

var child1 = new Child("Laura");
var child2 = new Child();

console.log(child1.name, child2.name); // "Laura", "The name property is empty"

它完美无缺,但我不明白会发生什么。我忘记了this,我无法按照call()方法的流程进行操作。这会将构造函数体从Parent复制到Child还是什么? this对象在哪里?它为什么有效?

请帮助并描述一下这个过程,我不明白。

1 个答案:

答案 0 :(得分:22)

首先,停止执行Child.prototype = new Parent();继承,除非您的浏览器不支持任何其他替代方案。这是一种非常糟糕的风格,可能会产生不良副作用,因为它实际上运行了构造函数逻辑。

您现在可以在每个现代浏览器中使用Object.create

Child.prototype = Object.create(Parent.prototype);

请注意,在此之后,您还应修正constructor Child.prototype的{​​{1}}属性,使其正确指向Child而不是Parent

Child.prototype.constructor = Child;

接下来,call如何运作?好call允许指定在执行函数时this关键字将引用哪个对象。

function Child(name){
  //When calling new Child(...), 'this' references the newly created 'Child' instance

  //We then apply the 'Parent' constructor logic to 'this', by calling the 'Parent' function
  //using 'call', which allow us to specify the object that 'this' should reference 
  //during the function execution.
  Parent.call(this, name);
}