Moolla
Moolla

Reputation: 169

Difference between an Object and its Prototype

Why does:

console.log(Object.hasOwnProperty("hasOwnProperty"));   

return a false, But:

console.log(Object.prototype.hasOwnProperty("hasOwnProperty"));  

return a true statement?

I realize that hasOwnProperty is a pre-built method in the Object but I guess my question is what is the difference between the Object and the prototype of an Object.
Aren't they one and the same?
When we refer to the Object in the first line of code, aren't we referring to the same line of code in the second line of code above?

EDIT: fixed above 2 lines of code from:

console.log(Object.hasOwnProperty);

and:

console.log(Object.prototype.hasOwnProperty);  

Upvotes: 0

Views: 183

Answers (2)

Bergi
Bergi

Reputation: 664207

I realize that hasOwnProperty is a pre-built method in the Object.

Actually its a function on a non-enumerable property of the object from which all JavaScript objects inherit. This includes the Object function object.

but I guess my question is what is the difference between the Object and the prototype of an Object. Aren't they one and the same?

No, they're definitely not. The section on Objects in the Language Overview of the EcmaScript specification describes it pretty well I think. Each object has a hidden [[prototype]] link to the object it inherits from (until null) - building the "prototype chain" in which properties are looked up. The public prototype property of functions is different from that - it points to the object from which all instances that are constructed by the function will inherit.

Upvotes: 0

Šime Vidas
Šime Vidas

Reputation: 185883

Both Object.hasOwnProperty and Object.prototype.hasOwnProperty reference the same function. Object.prototype contains that function as an own property, while Object contains it as an inherited property.

So, in other words, the hasOwnProperty function is defined (as a method) on the Object.prototype object. Then, the Object constructor (like almost all other native objects) inherits (all methods) from Object.prototype.

Btw, the inheritance chain (prototype chain) of Object is:

Object -> Function.prototype -> Object.prototype -> null

So, Object inherits all methods from both Function.prototype, and Object.prototype.

Upvotes: 1

Related Questions