Chris M
Chris M

Reputation: 4115

Function.prototype.propertyname === Object.propertyname is true?

In trying to better understand the prototype behind javascript, I have stumbled upon the following, which I am unable to make sense of so far.

I understand that functions are a first class object, but I don't get why Object gets this property after setting the property on Function.prototype

Function.prototype.foo = 'bar';

Object.foo // Object now has this property and returns 'bar'

Object.foo === Function.prototype.foo // returns true

Upvotes: 3

Views: 93

Answers (3)

rdleal
rdleal

Reputation: 1032

This is because Object and Function objects share the same internal [[Prototype]] property.

As Ecma-262 says:

The value of the internal [[Prototype]] property of the Function prototype object is the Object prototype object.

So if you add any property to the Function's prototype, that property will be accessible through the Object object too, and vice versa.

If you want to understand it deeply, I'd suggest you to take a look at the Ecma-262 Specification.

Hope it helps.

Upvotes: 1

xdazz
xdazz

Reputation: 160833

Object is a function, typeof Object == 'function' is true. So you assign a property of Function.prototype, it will let the Object has the property also. (in the property chain.)

Upvotes: 3

reagan
reagan

Reputation: 653

If I am not mistaken Function.prototype is a prototype for all inherited objects. Because you set Function.prototype.foo = 'bar'; all objects inherit the foo property. That is why the third line of code returns true.

Upvotes: 2

Related Questions