samedi 29 novembre 2014

Can't access methods on object's prototype


I can create a Cat object and set a method on it's prototype to print out the cat's name.





var log = function(message) {
var results = $('#result');
results.append('<p>' + message + '</p>');
};

function Cat(name) {
this.name = name;
}

Cat.prototype.speak = function() {
log('My name is ' + this.name);
};

var fluffy = new Cat('Fluffy');
var tiddles = new Cat('Tiddes');

log(fluffy.name);
fluffy.speak();
log(tiddles.name);
tiddles.speak();



<script src="http://ift.tt/1oMJErh"></script>
<div id="result"></div>



However, when I try to set the cat's prototype to an animal, I can't access the speak method:



function Animal(name, sound) {
this.name = name;
this.sound = sound;

this.speak = function() {
log(sound + '! My name is ' + name);
};
}

function Cat(name) {
this.prototype = new Animal(name, 'Meow');
}

var fluffy = new Cat('Fluffy');

fluffy.speak(); // TypeError: undefined is not a function


Why does fluffy not get the speak() method of its prototype?





Aucun commentaire:

Enregistrer un commentaire