我知道它有效,但我不知道为什么以及如何。有哪些机制?
// 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()
or the apply()
方法。致电“超一流" (the 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"
它工作完美,但我不明白会发生什么。我失去了this
在我的脑海里,我无法遵循这个过程call()
方法。是否从复制构造函数体Parent
to the Child
或者是什么?哪里是this
目的?为什么它有效?
请帮忙描述一下过程,我不太明白。