Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do we have Function.call in javascript?

Tags:

javascript

> Function.call == Function.prototype.call
true
> Function.prototype == Function
false

Why do Function.prototype.* methods exist as Function.*? It seems inconsistent.

This isn't the case with any other primary type (Array.slice doesn't exist but Array.prototype.slice does).

like image 853
Louay Alakkad Avatar asked Jan 15 '16 09:01

Louay Alakkad


People also ask

Why do we use function call?

A function is a set of code that performs a specific task and can be used whenever needed just by calling it. While using multiple function calls or recursion, the concept of a function call is very necessary to be known, for better understanding of the code.

What does it mean to call a function in JavaScript?

Javascript Function call() The JavaScript Function call() method calls a function with a given this value and arguments provided individually. The call() method calls a function by passing this and specified values as arguments.


1 Answers

Because Function itself is the prototype of Function

console.log(Function instanceof Function);
console.log(Object.getPrototypeOf(Function) === Function.prototype);

So, all the functions in the Functions prototype are available in Function also.

Quoting the specification,

The Function prototype object is itself a Function object (its [[Class]] is "Function")


Another way to confirm this would be,

console.log(Function.call === Function.prototype.call);

it means that the Function.call object and Function.prototype.call object are the same.

console.log(Function.hasOwnProperty('call'));

it means that the Function object itself doesn't have call property.

console.log(Function.prototype.hasOwnProperty('call'));

it means that Function.prototype object has the call property.


Array.slice doesn't exist but Array.prototype.slice do

Because Array function's prototype is Function object, not the Array object.

console.log(Object.getPrototypeOf(Array) === Function.prototype);

That is why we get call, apply, bind etc on the Array function. It Array object had been the prototype of Array, then slice would have been available on the Array object also.

like image 176
thefourtheye Avatar answered Sep 29 '22 14:09

thefourtheye