为什么--在下面的代码中--第3行工作而第4行不工作?
function out(x) {
console.log(x);
}
out.call(window, "bla") // outputs "bla"
out.call.bind(window, "bla")(); // throws "TypeError: object is not a function"发布于 2013-09-12 12:09:47
问题是您可能有一个错误:您打算编写out.bind(window, "bla")(),这将产生与调用相同的结果。
为什么使用当前代码出现错误?out.call.bind返回一个将call中的this的值修正到window的函数。然而,call期望this是一个函数,而window不是。结果是给定的错误。
来自带注释的ES5规范
15.3.4.5 Function.prototype.bind (thisArg [,arg1,arg2,…]) 绑定方法接受一个或多个参数( thisArg和(可选) arg1、arg2等),并通过执行以下步骤返回一个新函数对象: 1.将Target设为此值。2.如果IsCallable(Target)为false,则抛出一个TypeError异常。..。
您将得到一个预期的TypeError。
附录
out.call.bind的使用,与类似的out.call.call非常相似,结果是“重定向out.call的目标”--也就是说,不是在out上调用call,而是在其他事情上调用call。举个例子:
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" 42https://stackoverflow.com/questions/18763822
复制相似问题