I am experimenting with an inheritance model which combines the dynamic prototype pattern with prototype chaining. This investigation is purely academic as an attempt to understand the properties of objects in JavaScript. I'm sure better models could be recommended. I am curious as to why the combination of these two methods is failing to produce the prototype chain I am looking for.
function Animal(params) {
this.species = undefined;
this.sound = undefined;
if (params.species !== undefined){ this.species = params.species; }
if (params.sound !== undefined){ this.sound = params.sound; }
if (Animal.prototype.makeSound === undefined) {
Animal.prototype.makeSound = function() {
console.log(this.sound);
};
}
}
function Bear(params) {
if (params.species === undefined){ params.species = "Bear"; }
if (params.sound === undefined){ params.sound = "Grr"; }
Animal.call(this, params);
if (Bear.prototype.swipe === undefined) {
Bear.prototype = new Animal(params);
Bear.prototype.swipe = function() {
console.log("swipe - '" + this.sound + "'");
};
}
}
var bear = new Bear({});
bear.swipe(); // Uncaught TypeError: bear.swipe is not a function(…)
bear.makeSound(); // Uncaught TypeError: bear.makeSound is not a function(…)
If I move the prototype definitions outside of the constructor (ie no longer dynamic pattern) this works fine - with a removal of the params in the chaining call & a check around the params use in the Animal constructor :
function Animal(params) {
this.species = undefined;
this.sound = undefined;
if (params !== undefined) {
if (params.species !== undefined){ this.species = params.species; }
if (params.sound !== undefined){ this.sound = params.sound; }
}
}
Animal.prototype.makeSound = function() {
console.log(this.sound);
}
function Bear(params) {
if (params.species === undefined){ params.species = "Bear"; }
if (params.sound === undefined){ params.sound = "Grr"; }
Animal.call(this, params);
}
Bear.prototype = new Animal();
Bear.prototype.swipe = function() {
console.log("swipe - '" + this.sound + "'");
}
var bear = new Bear({});
bear.swipe(); // swipe - 'Grr'
bear.makeSound(); // Grr
I think this is reason to not bother with the dynamic pattern in real projects. I'm just curious is all.
The full example of what I am trying to do is here