JavaScript: call vs call.bind

Why - in the following code - line 3 works, but line 4 does not?

function out(x) { console.log(x); } out.call(window, "bla") // outputs "bla" out.call.bind(window, "bla")(); // throws "TypeError: object is not a function" 
+4
source share
1 answer

The problem is that you probably have a typo: instead, you should write out.bind(window, "bla")() , which will lead to the same result as the working call.

Why is there an error with the current code? Well out.call.bind returns a function that captures the value of this from call to window . However, call expects this be a function that window not. The result is a given error.

From the annotated specification of ES5 :

15.3.4.5 Function.prototype.bind (thisArg [, arg1 [, arg2, ...]])

The bind method takes one or more arguments, thisArg and (optionally) arg1, arg2, etc., and returns a new function object by following these steps:

 1. Let Target be the this value. 2. If IsCallable(Target) is false, throw a TypeError exception. [...] 

You get a TypeError as expected.

Adding

Using out.call.bind , like the similar out.call.call , leads to the "redirecting the target" to out.call - that is, instead of a call being called to out , it will be called to something else. Example:

 function foo(x) { console.log("this", this, "foo", x); } function bar(x) { console.log("this", this, "bar", x); } foo.call.bind(bar, window, 42)(); // "this" [window] "bar" 42 
+4
source

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


All Articles