domscripter
domscripter

Reputation: 27

JavaScript prototype issue

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:

  1. console.log(lucy.say());
  2. console.log(benji.paws);
  3. 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

Upvotes: 2

Views: 158

Answers (1)

Felix Kling
Felix Kling

Reputation: 816334

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).

Upvotes: 6

Related Questions