3

I'm playing around in the console, trying to understand prototypal inheritance. I'm familiar with classical inheritance, but I've never used any inheritance in my JS work.

If I have:

var foo = {
    cat: "oliver"
}

var bar = Object.create(foo);

foo.prototype = {
    dog: "rover"
}

When I do:

dir(bar.dog)

or

dir(foo.dog)

I expect to see rover but they both come back as undefined.

What am I missing?

Thanks in advance.

Ibrahim Najjar
  • 19,178
  • 4
  • 69
  • 95
  • I guess where I am confused is this: the prototype property on works on instantiated objects (functions) and yet Object.create is able to use an object literal as a prototype? Or does that pattern only work with constructors? –  Oct 13 '13 at 20:15
  • You cannot set prototype on object instances (like the foo object literal) and expect it to work like setting prototype on Functions. All you did was add a property named prototype on foo but JS runtime won't use it to look up. David has given the most correct answer. More info on what prototype is: http://stackoverflow.com/a/16063711/1641941 – HMR Oct 14 '13 at 04:27

3 Answers3

3

You are seeing this because of this line:

foo.prototype = {
    dog: "rover"
}

You can't change an object's prototype after you create that object.

What you can do is modify the existing prototype like this:

foo.dog = "rover";

Remember that foo is the prototype of bar.

Ibrahim Najjar
  • 19,178
  • 4
  • 69
  • 95
2

The prototype members are only available when you instantiate it. foo.cat is available because it's like "a static" property (from languages that have this kind of code support, like PHP for example). Also, you should inherit from the foo prototype when doing your Object.create

var foo = function(){ };
foo.cat = "oliver";

var bar = Object.create(foo.prototype);

foo.prototype.dog = "rover";

console.log(bar.dog); // yields "rover", modifying the prototype of "foo" alter the members of "bar" instance
pocesar
  • 6,860
  • 6
  • 56
  • 88
1

this would be the correct code to accomplish what you are trying:

var foo = Object.create({dog:'rover'});

foo.cat = 'oliver';

var bar = Object.create(foo);

this way foo inherits from an object with a property called dog, then bar inherits from that same object because it inherits from foo

Now, check with bar.dog and bar.cat it prints rover and oliver respectively

notice that .prototype only works to access or set the prototype object of functions, what you're doing in that code is wrong, this is correct:

var a = function(){
}

a.prototype = {};

to access the prototype of an object you do it like this:

a = {};

a.\__proto__.foo = 'bar';

however this allows you to get or set properties of that prototype object but not replace it for a different one.

exexzian
  • 7,782
  • 6
  • 41
  • 52
David V
  • 185
  • 8