我知道它有效,但我不知道为什么以及如何。机制是什么?
// 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
调用“super class”(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
对象在哪里?为什么有效?
请帮忙描述一下过程,我不懂。
最佳答案
首先,停止使用 Child.prototype = new Parent();
进行继承,除非您的浏览器不支持任何其他选择。这是一种非常糟糕的风格,可能会产生不良副作用,因为它实际上运行的是构造函数逻辑。
您现在可以在每个现代浏览器中使用 Object.create
。
Child.prototype = Object.create(Parent.prototype);
请注意,在此之后您还应该修复 Child.prototype
的 constructor
属性,使其正确指向 Child
而不是 父级
。
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);
}
关于Javascript 在 Child 中调用 Parent 构造函数(原型(prototype)继承) - 它是如何工作的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27018033/