I have the following Pet and cat inherits from Pet, as follows:
function Pet(){};
Pet.prototype.run = function takeoff(cb, sec) {
setTimeout(function() {
cb();
console.log('Run');
}, sec);
};
Pet.prototype.bark = function bark(cb, sec) {
setTimeout(function() {
cb();
console.log('bark');
}, sec);
};
Pet.prototype.comeback = function comeback(cb, sec) {
setTimeout(function() {
cb();
console.log('Comeback');
}, sec);
};
var cat = new Pet();
cat.prototype = Object.create(Pet);
cat.prototype.run = function(){
var that = this;
that.run = Pet.prototype.run.call(that);
return that;
}
cat.prototype.bark = function(){
this.bark = Pet.prototype.bark.call(this);
return this;
}
cat.prototype.comeback = function(){
this.comeback = Pet.prototype.comeback.call(this);
return this;
}
console.log(cat);
cat.run().bark().return();
In this situation, the cat and Pet have the same function names. The only difference is return this is added to cat methods to make method chaining possible in cat but not Pet. However, note that I have to write the name of the function every time and set the same name to its parent's prototype. Is it possible to generalize this so that any method I specify for Pet will be duplicated in cat but yet I don't have to specify the method for cat every time?