function Foo() {
this.SayFoo = function() {
console.log('Foo');
};
}
function Bar() {
this.SayBar = function() {
console.log('Bar');
};
}
Foo.prototype = new Bar();
var fooBar = new Foo();
fooBar.SayBar();
This obviously works, but is it the correct way to do it?
Is there any way to make use of jQuery’s $.extend or something similar in order to achieve the same inheritance results?
Including other frameworks besides jQuery is not an option in this case.
There are actually multiple ways to do inheritance in JavaScript: neoclassical, prototypal, and functional. Douglas Crockford has nothing but bad things to say about neoclassical inheritance—the method you have above, and the method most Java/C# developers think will be the most natural. The reason revolves around all the awkward things you have to do to get it right—setting the prototype, setting the constructor, etc. Also, setting the prototype to a
newinstance of the parent class, like you have above, is usually frowned upon strongly, I believe because it complicates handling parameters with the base ctor.If you’re really sold on the neoclassical method, here’s a great link that really goes over it.
The key part I reproduce for you here:
FWIW Here’s an example of functional inheritance that also highlights something you don’t get with the neoclassical method: encapsulation/information hiding.