Set a property to JS function's prototype

412 Views Asked by At

I create function and add property in its prototype as following

let F = function(){}
 F.prototype.foo = 'abc'

My question is why it will return undefined when using the F.foo? But after using this

let F = function() {}
F.prototype.foo = 'abc'
let fn = new F()
console.log(fn.foo) // return 'abc'

1

There are 1 best solutions below

0
On

foo is a property of the prototype object, one which instances have an internal prototype of when instantiated. This is not the same thing as the constructor function, which is completely different.

When you call the constructor function, you get an instance in return, but the constructor is not an instance or the instance's prototype.

This is how the prototype chain works here:

Object.prototype -> Function.prototype -> F

Object.prototype -> F.prototype -> fn

When you set something on F.prototype, it's nowhere on F's internal prototype chain - it's only on the prototype chain of instances.

If you set something on Object.prototype, both F and the fn instance would inherit it:

let F = function() {}
Object.prototype.foo = 'abc'
let fn = new F()
console.log(fn.foo) // return 'abc'
console.log(F.foo);

This works because Object.prototype is within both of their prototype chains.

(But that's just to give you an idea of how things work - in actual code, you should not mutate Object.prototype)