Reputation:
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.
Upvotes: 2
Views: 99
Reputation: 7050
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
Upvotes: 2
Reputation: 185
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.
Upvotes: 1
Reputation: 19423
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
.
Upvotes: 3