Is there any other way to override a prototype function while still calling the base function and inherit its constructor other than what I’m doing below?
function MyFoo(name) {
this.name = name;
}
MyFoo.prototype.sayName = function() {
alert("Hi, my name is " + this.name + ".");
}
MyBar.constructor = MyFoo;
MyBar.prototype = new MyFoo();
function MyBar(name) {
MyFoo.apply(this, arguments);
};
MyBar.prototype.sayName = function() {
MyFoo.prototype.sayName.call(this);
alert("It's nice to meet you!");
}
var fooJim = new MyFoo("Jim");
var barJake = new MyBar("Jake");
fooJim .sayName();
barJake .sayName();
This works fine, but I’m just curious if there is a more efficient way to do it.
No, your approach to emulate class inheritance is intrinsically as minimalist at the JavaScript language allows.
If you want to make a massive usage of class inheritance in your application and want to minimize redundant code, you might either:
I also can’t help to advice this book (hope it won’t be considered as spam): “JavaScript Patterns” by Stoyan Stefanov. It has a very good chapter on different technics to emulate class inheritance in javascript.