简体   繁体   中英

Javascript Simple Prototypal Inheritance

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.

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 .

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM