So che funziona, ma non so perché e come. Quali sono i meccanismi?JavaScript call Costruttore genitore nel bambino (eredità prototipica) - Come funziona?
// 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
So quello che mi serve, il call()
o il metodo apply()
. Chiama la "super classe" (il costruttore Parent
) da Child
e passa l'oggetto this
e l'argomento name
a quello. Funziona:
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"
Funziona perfettamente, ma non capisco cosa succede. Ho perso il this
nella mia mente e non posso seguire il processo del metodo call()
. Copia il corpo del costruttore da Parent
a Child
o cosa? E dov'è l'oggetto this
? Perché funziona?
Si prega di aiutare e descrivere il processo, non capisco.
vedono questo: http: //stackoverflow.com/questions/20830449/object-create-changes-prototype-constructor-to-parent-constructor-but-upon-chil –
https Correlati: // StackOverflow. com/a/29543030/632951 – Pacerier
La mente accetta la risposta? – plalx