Javascript call Parent constructor in the Child (prototypical inheritance) - How it works? -
i know works, don't know why , how. mechanics?
// parent constructor function parent(name){ this.name = name || "the name property empty"; } // child constructor function child(name){ this.name = name; } // originaly, child "inherit" parent, name property, in case // shadowing name property in child constructor. child.prototype = new parent(); // want this: if dont set name, please inherit "the name property empty" // parent constructor. know, doesn't work because shadow in child. var child1 = new child("laura"); var child2 = new child(); //and result undefined (of course) console.log(child1.name, child2.name); //"laura", undefined
i know need, call()
or apply()
method. call "super class" (the parent
constructor) child
, , pass this
object , argument name
that. works:
function parent(name){ this.name = name || "the name property empty"; } function child(name){ // call "super class" do? how work? don't understand process, lost 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 empty"
it works perfectly, don't understand happens. lost this
in mind, , can't follow process of call()
method. copy constructor body parent
child
or what? , this
object? why work?
please , describe process, don't understand.
first of all, stop doing child.prototype = new parent();
inheritance, unless browser doesn't support other alternative. that's bad style , can have undesired side effects, since runs constructor logic.
you can use object.create
in every modern browser now.
child.prototype = object.create(parent.prototype);
please note after should fix constructor
property of child.prototype
correctly points child
rather parent
.
child.prototype.constructor = child;
next, how call
works? call
allows specify object referenced this
keyword when function executed.
function child(name){ //when calling new child(...), 'this' references newly created 'child' instance //we apply 'parent' constructor logic 'this', calling 'parent' function //using 'call', allow specify object 'this' should reference //during function execution. parent.call(this, name); }
Comments
Post a Comment