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

KMS*_*KMS 11 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
Run Code Online (Sandbox Code Playgroud)

我知道我需要什么,call()或者apply()方法.从中调用" 超类 "(Parent构造函数)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"
Run Code Online (Sandbox Code Playgroud)

它工作得很好,但我不明白会发生什么.我失去了this我的想法,我不能按照call()方法的过程.是否将构造函数体复制Parent到了Child什么?this对象在哪里?它为什么有效?

请帮忙描述一下这个过程,我不明白.

pla*_*alx 22

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

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

Child.prototype = Object.create(Parent.prototype);
Run Code Online (Sandbox Code Playgroud)

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

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

接下来,如何call运作?Well 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);
}
Run Code Online (Sandbox Code Playgroud)