J. Doe
J. Doe

Reputation: 3

call() and apply() Javascript?

var a = function() { }; //Just a function

When I run a.__proto__ in the console, it returned this

function () {}

So, if prototype of every function created in javascript is a function like the above, then where exactly methods like call(), apply() and bind() defined?

Upvotes: 0

Views: 106

Answers (2)

Felix Kling
Felix Kling

Reputation: 816374

if prototype of every function created in javascript is a function like the above, then where exactly methods like call(), apply() and bind() defined?

Exactly on that function / pobject. Function.prototype is a function, but it is not like any other. It's defined §8.2.2 CreateIntrinsics:

8. Let noSteps be an empty sequence of algorithm steps.
9. Let funcProto be CreateBuiltinFunction(realmRec, noSteps, objProto).
10. Set intrinsics.[[%FunctionPrototype%]] to funcProto.

It is a built-in function, but its own prototype is set to the default object prototype (objProto) here, not to itself (you cannot have circular prototype chains).

Step 13 in that algorithm then goes and says that all intrinsic values need to be recursively initialized according to some people and certain sections in the spec:

Set fields of intrinsics with the values listed in Table 7 that have not already been handled above. The field names are the names listed in column one of the table. The value of each field is a new object value fully and recursively populated with property values as defined by the specification of each object in clauses 18-26. [...]

The table contains:

%FunctionPrototype% | Function.prototype | The initial value of the prototype data property of %Function%

and §19.2.3 describes all the properties of that object, including the ones you mentioned.

Upvotes: 0

James Thorpe
James Thorpe

Reputation: 32202

The functions do exist on a.__proto__ (or further in the chain) - the issue you're seeing is more of how it's being represented in the console. For instance, if you just do a in the console, you'd also see the empty function string, but without the __proto__ property, which you already know is there.

As @squint pointed out in the comments, if you use console.dir the other properties will be shown:

enter image description here

Upvotes: 3

Related Questions