Is it possible to call parent method in JavaScript class but to still have access to prototype methods from parent and child class. Here is code example:
var Base = function() {
this.baseMethod = function(){
return 'baseMethod';
};
this.baseInitMethod = function() {
return 'baseInitMethod';
}
}
Base.prototype.basePrototypeMethod = function() {
return "basePrototypeMethod";
};
var Specific = function() {
Base.call(this);
this.baseInitMethod = function() {
// call baseInitMethod from Base class
}
this.specificMethod = function(){
return 'specificMethod';
}
this.specificInitMethod = function() {
return this.basePrototypeMethod();
}
}
Specific.prototype.specificPrototypeMethod = function() {
return 'specificPrototypeMethod' + '-' + this.baseInitMethod();
}
for(var p in Base.prototype) {
Specific.prototype[p] = Base.prototype[p]
}
var s = new Specific();
console.log(s.baseMethod());
console.log(s.baseInitMethod());
console.log(s.basePrototypeMethod());
console.log(s.specificMethod());
console.log(s.specificInitMethod());
console.log(s.specificPrototypeMethod());
I want to call baseInitMethod in Base class from baseInitMethod method inside Specific class but so that all function calls from above still works. Is that possible?
Your
Specific.prototype
object should inherit from theBase.prototype
object. Currently you're copying over all its properties to the object with this code:But you should actually use
Object.create
to establish a real prototype chain:Yes. In your
Specific
constructor, you first need getBase
'sbaseInitMethod
instance method, before you overwrite the property of the instance:I'm not sure what you mean by that exactly. The
specificPrototypeMethod
will always call thebaseInitMethod
of the current instance, which would beSpecific
's overwritten one not the original that was defined inBase
.You're overwriting the
baseInitMethod
ofBase
insideSpecific
, withSpecific
's definition, so why would you ever want to call the Base version? If you simply remove the overwrite of the function you should call the Base definition:Here is what you need to do:
One might argue "Why always trying to mimic 'classical' behaviour and fuss with
call
andapply
instead of embracing the prototype delegation pattern instead?"Here is what I would code :