简体   繁体   中英

JavaScript: call vs call.bind

Why does - in the following code - line 3 work and 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"

The problem is that you probably have a typo: you meant to write out.bind(window, "bla")() instead, which would produce the same result as the call that works.

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

From the annotated ES5 specification :

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 performing the following steps:

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

You are getting a TypeError as expected.

Addendum

The out.call.bind usage, much like the similar out.call.call , results in "redirecting the target" of out.call -- that is, instead of call being invoked on out , it will be invoked on something else. An 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM