some modification of your code (1 line):
.......
var init = function() {
console.log('init');
//customInit.call(this);
this.customInit.call(this);
},
.....
Вопрос
I'm currently struggling with some concepts and syntax for the Revealing Prototype Pattern in Javascript. Could you guys help me understand it?
What I am trying to achieve: call an overridden method from another method of the base class.
How I did it:
Base class:
var Base = function() {
//...
};
Base.prototype = function() {
var init = function() {
console.log('init');
customInit.call(this);
},
customInit = function() {
console.log('custom init source');
};
return {
init: init,
customInit: customInit
};
} ();
Extended class:
var Extended = function () {
//...
};
Extended.prototype = new Base();
Extended.prototype.customInit = function () {
console.log('custom init extended');
};
Call to extended class:
window.addEventListener('load', function (){
var myObject = new Extended();
myObject.init();
myObject.customInit();
});
The call to customInit
from outside of the class executes the overriden version of the method (what I want), while the call from within the class still calls the "base" version of the method (not what I want).
Is this normal? Is there any workaround to achieve this?
Решение
some modification of your code (1 line):
.......
var init = function() {
console.log('init');
//customInit.call(this);
this.customInit.call(this);
},
.....
Другие советы
You can call a parent function in child with Parents.prototype. some function.call(this, param1, param2)
For more info you can check out this answer:https://stackoverflow.com/a/16063711/1641941