JavaScript prototype prototype

I was trying to find out how the object.prototype function in javascript, then I came across this piece of code that I don't understand?

// Poisoning Object.prototype Object.prototype.bar = 1; var foo = {goo: undefined}; foo.bar; // 1 'bar' in foo; // true foo.hasOwnProperty('bar'); // false foo.hasOwnProperty('goo'); // true 

foo has a property bar, which is defined in line number 3 and has the value undefined. Please indicate why foo.hasOwnProperty('bar') returns false in this case

+5
source share
3 answers

All objects in JavaScript come from Object . all objects inherit methods and properties from Object.prototype .

In your example, when you try to get foo.bar , it does not find bar in foo , so it is going to prototype foo and trying to find it there.

hasOwnProperty - checks only the property that is located exactly in your foo .

Here is what your foo looks like

enter image description here

For a deeper understanding, you can read this chapter.

You don't know js

+4
source

The foo object has a bar property because it inherits it from Object since bar was added to the prototype of the object. foo.hasOwnProperty('bar') returns false because foo does not define bar , Object does.

0
source

This simple goo is a direct property of foo, but in order to get a bar, you need to go through a prototype chain. hasOwnProperty only checks its property.

0
source

All Articles