How do you get inheritance working within JavaScript? -


i want constructor paper inherit constructor view. i've read there needs temporary constructor new f(), parent modified along child class prototype in code:

function view() {}; function paper() {};  view.prototype = {     location: {         "city": "uk"     } }   function f() {};  f.prototype = view.prototype; paper.prototype = new f(); paper.prototype.constructor = paper; 

so when try modify paper's prototype:

paper.prototype.location.city = "us"; 

i find view's prototype modified too!:

var view = new view(); console.log(view.location); //us! not uk 

so what's wrong code? how can override prototype without affecting parent?

inheritance in js tricky, you've discovered. perhaps smarter can enlighten on technical specifics why, possible solution use very tiny base.js framework, courtesy of dead edwards.

edit: have restructured original code fit dean edward's framework.

inheritance work once master syntax. here's possible solution based on code:

var view = base.extend({     constructor: function(location) {         if (location) {             this.location = location;         }     },      location: "uk",      getlocation: function() {         return this.location;     } }); 

and extending it:

var paper = view.extend({     location: "us" }); 

and testing it:

var view = new view(); alert("the current location of view is: " + view.getlocation()); var paper = new paper(); alert("the location of paper is: " + paper.getlocation()); alert("the current location of view is: " + view.getlocation()); 

alternatively, same result can achieved with:

var paper = view.extend(); 

and testing:

var view = new view(); alert("the current location of view is: " + view.getlocation()); var paper = new paper("us"); alert("the location of paper is: " + paper.getlocation()); alert("the current location of view is: " + view.getlocation()); 

both produce 3 alerts:

the current location of view is: uk location of paper is: current location of view is: uk 

i hope helps!


Comments

Popular posts from this blog

php - get table cell data from and place a copy in another table -

javascript - Mootools wait with Fx.Morph start -

php - Navigate throught databse rows -