prototype - For JavaScript prototypal inheritance, why can't a parent object be created and saved in a child's constructor? -
in javascript code, when instantiation of new child
causes constructor execute, create method not seem creating parent object. child not seem inherit parent's member function m
.
function parent() { parent.prototype.a =2; parent.prototype.m = function() { return this.a++; } } function child() { child.prototype = object.create(parent.prototype); child.prototype.constructor = parent; parent.call(this); } var c = new child(); alert(child.prototype.m()); // 2 alert(child.prototype.m()); // 3 alert(c.m()); // fails!!!
your prototype methods , inheritance should defined outside of functions...
function parent() { } parent.prototype.a =2; parent.prototype.m = function() { return this.a++; } function child() { parent.call(this); } child.prototype = object.create(parent.prototype); var c = new child(); alert(child.prototype.m()); // 2 alert(child.prototype.m()); // 3 alert(c.m()); // 4
Comments
Post a Comment