class - In JavaScript, how can you access a property of a superclass' instance? -


in javascript, how can access property of superclass' instance? example, i'd "prop" of superclass' instance set "true", code creates , sets "prop" of subclass' instance "true", leaving superclass' instance's "prop" false:

var superclass = function() {     this.prop = true; }  superclass.prototype.dostuff = function() {      if (this.prop) {         console.log('superclass a.');     }     else {         console.log('superclass b.');     } }  superclass.prototype.load = function() {     this.prop = false; }  superclass.prototype.setprop = function(val) {     this.prop = val; }  function subclass() {     superclass.call(this); }  subclass.prototype = object.create(superclass.prototype); subclass.prototype.constructor = subclass;  subclass.prototype.dostuff = function() {     superclass.prototype.dostuff();      if (this.prop) {         console.log('subclass a.');     }     else {         console.log('subclass b.');     } }  subclass.prototype.load = function() {     superclass.prototype.load(); }  var anobject = new subclass(); anobject.load(); anobject.setprop(true); anobject.dostuff(); 

currently, output "superclass b. subclass a.", not desired result. how set value of "prop" both "a"? i'm not trying create new property in subclass' instance, want access existing property in superclass' instance.

thanks!

additionally, can access superclass' instance's properties subclass' constructor? or subclass need instantiated first?

subclass.prototype.dostuff = function() {     superclass.prototype.dostuff(); 

you aren't giving super class context, function isn't acting on current object (i.e. this wrong).

instead try:

subclass.prototype.dostuff = function() {     superclass.prototype.dostuff.call(this); 

this gives me desired output:

superclass a. subclass a. 

Comments

Popular posts from this blog

dns - How To Use Custom Nameserver On Free Cloudflare? -

python - Pygame screen.blit not working -

c# - Web API response xml language -