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'
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:
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
, bothF
and thefn
instance would inherit it: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
)