inheritance - How to invoke method which rewrite in sub class using javascript(es5) -
i hava 2 class, 1 base class called chartbase, other sub class called chartextend, code following:
/*base class defined*/ function chartbase(element, data, settings, type) { // this.init(); }; chartbase.prototype = { init:function(){ this.initconfig(); // other things; }, initconfig:function(){ this.setbaseconfig(); }, setbaseconfig:function(){ // something; } } /*sub class defined*/ function chartextend(element, data, settings, type) { chartbase.apply(this, arguments); }; chartextend.prototype = { initconfig:function(){ this.setbaseconfig(); this.setexternalconfig(); }, setexternalconfig:function(){ // something; } }; /*sub class extend base class*/ var tempclass = function() {}; tempclass.prototype = chartbase.prototype; chartextend.prototype = new tempclass(); chartextend.prototype.constructor = chartextend; chartextend.uber = chartbase.prototype; /*instance*/ new chartextend(selector, data, settings, 'line');
i found 'initconfig' method invoked in chartbase, not method in chartextend when created instance, however, 'this' pointed chartextend in 'init' function.
1. why still call own prototype method in chartbase?
2. how invoke rewrited method in chartextend?
first of all, overwriting methods defined in chartextend.prototype
when doing chartextend.prototype = new tempclass();
. that's why, when invoke initconfig
method, of chartbase
, not of chartextend
.
to correct this, need inherit classes base class methods can overridden sub class method. see below example.
// base class function chartbase() {} // prototype functions chartbase.prototype.initconfig = function() { console.log('base class :: initconfig'); } chartbase.prototype.setbaseconfig = function() { console.log('base class :: setbaseconfig'); } // sub class function chartextent() { chartbase.apply(this, arguments); } // extend base class chartextent.prototype = new chartbase() // define sub class prototypes chartbase.prototype.initconfig = function() { console.log('sub class :: initconfig'); this.setbaseconfig(); } // create instance var instance = new chartextent() // call instance method instance.initconfig()
Comments
Post a Comment