javascript - Proper way to call superclass functions from subclass -


i have "superclass" "info" instance variable. "superclass" has function "printinfo()". "printinfo()" needs access instance variable "info". want create "subclass" has method "printinfo()". want call printinfo() of "superclass" "printinfo()" of "subclass".

superclass = function() {     this.info = "i superclass";     console.log("superclass:"); };  superclass.prototype.printinfo = function(that) {     console.log("printing superclass printinfo");     console.log(that.info); };  subclass = function(){};  subclass.prototype = new superclass();  subclass.prototype.printinfo = function() {     console.log("calling superclass");     this.constructor.prototype.printinfo(this);     console.log("called superclass"); };  var sc = new subclass(); sc.printinfo(); 

you can see passing "that" parameter printinfo. without "that" parameter, "info" printed "undefined". in following case, "this.info" undefined when function called object of "subclass".

superclass.prototype.printinfo = function()     {         console.log("printing superclass printinfo");         console.log(this.info);     }; 

what proper way override , invoke methods of superclass in javascript, enabling functions access instance variables of class?

you messing subclass's prototype superclass's object, in line

subclass.prototype = new superclass(); 

the child's prototype should depend on parent's prototype. so, can inherit this

subclass.prototype = object.create(superclass.prototype); 

also, quite normal change constructor actual function, this

subclass.prototype.constructor = subclass; 

to keep implementation generic, can use object.getprototypeof, parent prototype in inheritance chain , invoke printinfo, this

subclass.prototype.printinfo = function() {     object.getprototypeof(subclass.prototype).printinfo(this); }; 

since, info defined in subclass yet, print undefined. might want call parent't constructor, this

var subclass = function() {     superclass.call(this); }; 

note: creating global variables, omitting var keyword before superclass , subclass.


Comments

Popular posts from this blog

apache - Remove .php and add trailing slash in url using htaccess not loading css -

inno setup - TLabel or TNewStaticText - change .Font.Style on Focus like Cursor changes with .Cursor -