我知道它有效,但我不知道为什么以及如何。有什么机制?
// 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
对象在哪里?它为什么有效?
请帮助并描述一下这个过程,我不明白。
答案 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);
}