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"
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"
问题是您可能有一个错字:您打算改为编写out.bind(window, "bla")()
,这将产生与有效调用相同的结果。
为什么当前代码出错?Well返回一个将within的out.call.bind
值固定为 的函数。但是,期望是一个函数,但事实并非如此。结果是给定的错误。this
call
window
call
this
window
来自带注释的 ES5 规范:
15.3.4.5 Function.prototype.bind (thisArg [, arg1 [, arg2, ...]])
bind 方法接受一个或多个参数,thisArg 和(可选)arg1、arg2 等,并通过执行以下步骤返回一个新的函数对象:
1. Let Target be the this value. 2. If IsCallable(Target) is false, throw a TypeError exception. [...]
你得到了TypeError
预期的结果。
这种out.call.bind
用法,很像类似的out.call.call
,导致“重定向目标” out.call
——也就是说,它不会被call
调用out
,而是会被其他东西调用。一个例子:
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