Wiem, że to działa, ale nie wiem dlaczego i jak. Jakie są mechanizmy?Wywołanie Javascript Konstruktor nadrzędny u dziecka (prototypowe dziedziczenie) - jak to działa?
// 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
wiem, co muszę, call()
lub metoda apply()
. Wywołanie "super klasy" (konstruktor Parent
) z Child
i przekazanie obiektu this
i argumentu name
. Działa:
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"
Działa doskonale, ale nie rozumiem, co się dzieje. Zgubiłem w moim umyśle this
i nie mogę śledzić procesu metody call()
. Czy to kopiuje korpus konstruktora z Parent
do Child
lub co? A gdzie jest obiekt this
? Dlaczego to działa?
Proszę pomóż i opisz proces, nie rozumiem.
patrz: http: //stackoverflow.com/questions/20830449/object-create-changes-prototype-constructor-to-parent-constructor-but-upon-chil –
pokrewnych https: // stackoverflow. com/a/29543030/632951 – Pacerier
Umysł akceptujący odpowiedź? – plalx