Currently, I'm reading 'Object-Oriented JavaScript'. In addition, I've encountered a hiccup while carrying out an example from the book.
Below is the code sample:
var Dog = function() {
this.tail = true;
};
var benji = new Dog();
var rusty = new Dog();
Dog.prototype.say = function() { return "Woof!"; };
benji.say();
rusty.say();
Dog.prototype = {
paws: 4,
hair: true
};
Dog.prototype.constructor = Dog;
var lucy = new Dog();
lucy.say();
Essentially, the idea is to have the following work:
- console.log(lucy.say());
- console.log(benji.paws);
- The obvious - lucy.say();
etc.
Strangely enough, I've copied the example to the 'T', but to no avail. If anyone could shed some light I'd be more than grateful.
Cheers
1 Answer 1
By doing
Dog.prototype = {
paws: 4,
hair: true
};
you create a totally new prototype object (you are assigning a new object to prototype). The method say() will be not available to new Dog objects nor will the properties paws and hair be available to the old ones.
You want:
Dog.prototype.paws = 4;
Dog.prototype.hair = true;
You can try:
console.log(benji.__proto__ === rusty.__proto__); // prints true
console.log(lucy.__proto__ === rusty.__proto__); // prints false
and console.dir(x.__proto__) should show you the properties of the prototype objects (at least in Chrome).
lucy.constructor.prototype.pawsbut it won't givelucythesaymethod.