What is the initial value of the prototype property of a JavaScript function?

I know that the prototype property of JavaScript function objects is copied to the internal [[Prototype]] (aka __proto__ ) property of objects created using the function as a constructor. Thus, I can set this property for any object that I want to use as a prototype:

 function Foo() {} Foo.prototype = { toString: function() { return "I'm a Foo!"; } } new Foo().toString() // --> "I'm a Foo!" 

It seems like a widespread practice is to add functions that should act as class methods for an existing prototype of newly created functions, such as:

 function Bar() {} Bar.prototype.toString = function() { return "I'm a Bar!"; } new Bar().toString() // --> "I'm a Bar!" 

However, it is not clear to me what the initial value of the prototype property is.

 function Baz() {} Baz.prototype // --> Baz { // constructor: function Baz() {}, // __proto__: Object // } 

The comment shows how the Chrome JavaScript console prints. Does this mean that every function I create actually creates two objects? One for the function itself ( constructor ) and one for its prototype?

Is it defined somewhere in the ECMAScript standard? I tried to find him, but could not. Do all browsers handle this the same way?

+6
javascript prototype
source share
1 answer

The initial prototype value for any newly created Function instance is a new Object instance, but with its own constructor property, to point to a new function.

This is described in the typical ECMAScript-spec specification of a fully-unreadable version of ECMA262-5 in section 13.2:

(16.) Let proto be the result of creating a new object, which will be created by the expression new Object() , where Object is the standard built-in constructor with this name

(17.) Call the prototype internal method [[DefineOwnProperty]] with arguments "constructor", property descriptor {[[Value]]: F, {[[Writable]]: true, [[Enumerable]]: false, [[Configurable ]]: true} and false.

(18.) Call the internal method F [[DefineOwnProperty]] with arguments "prototype", property descriptor {[[Value]]: proto , {[[Writable]]: true, [[Enumerable]]: false, [[Configurable ]]: false} and false.

+10
source share

All Articles