It seems like there are many ways implementing inheritance in JavaScript. Which version do you prefer or would you suggest another solution?
The code should run in IE8+ so my first version would not fit…
function Animal(name) {
this.name = name
}
Animal.prototype = {
eat: function() {
console.log(this.name + ': *eat*')
}
}
function Cat(name) {
Animal.call(this, name);
}
Cat.prototype = Object.create(Animal.prototype, {
miaou: {
value: function() {
console.log(this.name + ': *miaou*')
}
}
})
var garfield = new Cat("Garfield");
garfield.eat(); // Garfield: *eat*
garfield.miaou(); // Garfield: *miaou*
// ------------
//
// possible alternative:
// […] see http://ejohn.org/blog/simple-javascript-inheritance/ for definition
// of Class
var Animal2 = Class.extend({
init: function(name) {
this.name = name
},
eat: function() {
console.log(this.name + ': *eat*')
}
});
var Cat2 = Animal2.extend({
init: function(name) {
this._super(name)
},
miaou: function() {
console.log(this.name + ': *miaou*')
}
});
var garfield2 = new Cat("Garfield2");
garfield2.eat(); // Garfield: *eat*
garfield2.miaou(); // Garfield: *miaou*