【发布时间】:2015-01-17 00:59:36
【问题描述】:
我知道它有效,但我不知道为什么以及如何。机制是什么?
// 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() 方法。从Child 调用“超类”(Parent 构造函数),并将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 对象在哪里?为什么会起作用?
请帮忙描述一下过程,我不明白。
【问题讨论】:
标签: javascript constructor prototype call chain