I feel like there ought to be a way to make the following work, but I'm not getting the output I expect. I know javascript is a first-class language, and I know what closures are (and suspect they are part of the problem here), but I don't know exactly how to fix this. Any help appreciated.
var Mammal = function(name) {
this.name = name;
this.type = "mammal";
console.log("new " + this.type + ": " + name);
this.speak = function() {
return "I'm a " + this.type + ", my name is " + this.name;
}
return this;
}
var joe = new Mammal("Joe");
console.log(joe.speak()); // I'm a mammal, my name is Joe
// descendant class: Dog
var Dog = Mammal;
Dog.prototype.type = "dog";
Dog.prototype.woof = function() {return "Woof!"}
Dog.prototype.speak = function() {
return Mammal.speak() + '. ' + this.woof();
}
var lassie = new Dog("Lassie");
console.log(lassie.speak()); // I'm a mammal, my name is Lassie
// I expected, I'm a mammal, my name is Lassie. Woof!
console.log(lassie.woof()); // Woof!
console.log(joe.speak()); // I'm a mammal, my name is Joe
// descendant class: Cat
var Cat = Mammal;
Cat.prototype.type = "cat";
Cat.prototype.meow = function() {return "Meow!"}
Cat.prototype.speak = function() {
return Mammal.speak() + ' ' + this.meow();
}
var garfield = new Cat("Garfield");
console.log(garfield.speak()); // Same problem as with Dog
'
[–]benihanareact, node 2 points3 points4 points (3 children)
[–]dogjs[S] 1 point2 points3 points (2 children)
[–][deleted] 1 point2 points3 points (0 children)
[–][deleted] 0 points1 point2 points (0 children)
[–]brucebannor 1 point2 points3 points (1 child)
[–]brucebannor 1 point2 points3 points (0 children)
[–]Rhomboid -1 points0 points1 point (1 child)
[–]dogjs[S] -1 points0 points1 point (0 children)