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

Popular posts from this blog

asp.net mvc - SSO between MVCForum and Umbraco7 -

Python Tkinter keyboard using bind -

ubuntu - Selenium Node Not Connecting to Hub, Not Opening Port -