使用 Function.prototype.call 作为回调

msh*_*ang 3 javascript function callback

我在 Google Chrome 控制台中尝试了以下操作:

> function t1(f) { return f(1); }
> function t2() { return this+1; }
> t1(t2.call)
TypeError: object is not a function
Run Code Online (Sandbox Code Playgroud)

为什么这不起作用?有没有办法定义一个函数来代替 Function.prototype.call 可以在这里工作?

I H*_*azy 5

这是行不通的,因为当你通过时t2.call,你实际上只是通过了.call。换句话说,它不记得传递它的对象。


要完成您想要的操作,您可以使用.bind().

t1(t2.call.bind(t2))
Run Code Online (Sandbox Code Playgroud)

这将t2函数绑定为 的this.call,这意味着您将.call像执行此操作一样调用:

t2.call
Run Code Online (Sandbox Code Playgroud)

……这就是你想要的。


.bind方法在 IE8 及更低版本以及其他一些较旧的浏览器中不受支持,但在这些情况下您可以实现一个几乎完整的 shim。


仅供参考,如果您非常需要它,您可以将其绑定.call为调用上下文.bind以将其缩短一点。

var callBind = Function.prototype.bind.bind(Function.prototype.call);
Run Code Online (Sandbox Code Playgroud)

所以现在你有了一个.bind().call()bound 作为调用上下文的函数。当您调用它时,就好像您在执行以下操作:

.call.bind(/* the function */)
Run Code Online (Sandbox Code Playgroud)

SocallBind()将返回一个以the functionbound 作为 的调用上下文的函数.call,就像我们上面所做的那样。所以你会像这样使用它:

t1(callBind(t2))
Run Code Online (Sandbox Code Playgroud)