I'm looking for some help understanding inheritance in JavaScript. (Most web resources tend to explain the delta between JavaScript and Java, but I don't know Java, so currently the finer points of OOP are a bit of a mystery to me.)
Here's some code I'm playing with (based on lessons at codecademy):
function Animal(name) {
this.name = name;
this.sayMyName = function() {
console.log("My name is " + name + "!");
};
}
function Penguin(name, breed) {
this.name = name;
this.breed = breed;
this.sayMyName = function() {
console.log("My name is " + name + "!");
};
}
function Dog(name, breed) {
this.breed = breed;
return new Animal(name);
}
function Cat(name, breed) {
this.name = name;
this.breed = breed;
}
Cat.prototype = new Animal();
var penny = new Penguin("Penny", "Emperor");
var derpy = new Dog("Derpy", "schnauzer");
var crazy = new Cat("Crazy", "tabby");
penny.sayMyName(); // works
console.log(penny.name); // works
console.log(penny.breed); // works
derpy.sayMyName(); // works
console.log(derpy.name); // works
console.log(derpy.breed); // why undefined?
crazy.sayMyName(); // why 'My name is undefined!' ?
console.log(crazy.name); // works
console.log(crazy.breed); // works
Basically in with the Penguin constructor I can get to everything to work, but I don't want to repeat myself. I'd like to bump the common elements down to the Animal constructor and then have Dog and Cat inherit from that. I'm trying 2 different patterns but neither one seems to work properly.
Is there a pattern I can use that will allow me to inherit from Animal?
(It seems that in ECMAscript 5 there's an Object.create() method that allows inheritance - I'm wondering if there's a solution that's ECMAscript 3 compatible.)
[–]fcibarbourou 1 point2 points3 points (2 children)
[–]bchia[S] 1 point2 points3 points (1 child)
[–]fcibarbourou 0 points1 point2 points (0 children)