Why do functions respond to .prototype but there are no ordinary objects?

Consider:

function Foo() {} var x = new Foo(); 

now x and Foo have the same prototype, but only Foo responds to .prototype:

 Object.getPrototype(x) === Foo.prototype // true x.prototype === Foo.prototype // false Foo.prototype // Foo {} (depending on which browser) x.prototype // undefined 

Why doesn't x.prototype work, but Foo.prototype works?

+5
source share
2 answers

prototype is a property of constructors that determines what the prototype of the new objects created by this constructor will be. It is useful to have such a property in the constructor.

So far, the prototype constructor has not been changed:

 Object.getPrototypeOf( x ) === Foo.prototype 

and this is the same as:

 Object.getPrototypeOf( x ) === x.constructor.prototype 

Please note that usually:

 Object.getPrototypeOf( Foo ) != Foo.prototype 
+5
source

In short: functions intended for new have prototype , instance instances do not.

I will probably refuse my exactness to say this, but prototype is something that only applies to what you might call constructor functions, which are functions that must be called with new to create instances. The prototype can be considered as a template for the resulting instance.

For the resulting object, prototype not a property. Rather, the properties in the prototype constructor are available as properties of the instance that was created. This means that when searching for an instance property, if it is not defined in the instance, Javascript will begin to check the prototype chain to determine if the file exists there.

If you want to access the instance prototype, use Object.getPrototypeOf .

Javascript semantics can be misleading. I highly recommend working through the freely readable Javascript AllongΓ© to fully understand some of the intricacies of Javascript. Chapter 8 focuses on just this topic.

+1
source

Source: https://habr.com/ru/post/1240283/


All Articles