Bounded call of call function

slo2ols

I am curious how bounded call function works inside in Javascript. The confusing example:

Number.call.bind(Array)(undefined, 1, 2)

Output:

[1, 2]

Indeed, instead of Number I can write any function and that will be ignored. My assumption is at some moment Array is called as a constructor function and 1 and 2 are passing as parameters. My question is what inside of call function leads to such a strange behavior?

Thanks.

Felix Kling

call is not much different from any other function (expect it can set this somehow). Here is a pseudo-code pseudo-version of call:

function call(thisArg, ...args) {
    let boundThis = this.bind(thisArg);
    return boundThis(...args);
}

So, all it really does is setting this of the function to the fist argument passed and then passes the remaining arguments to the function.

call.bind(Array) binds this inside call to Array, i.e. it "fixes" the function to which .call is applied to Array, meaning it will now always call Array. So you essentially have

let boundThis = Array.bind(thisArg);
return boundThis(...args);

which is basically Array(...args).

この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。

侵害の場合は、連絡してください[email protected]

編集
0

コメントを追加

0

関連記事