延迟解析后调用的函数范围

Scope of function called after deffered resolved

我有一个函数需要等待另一个函数完成才能被调用,所以我尝试使用 jquery deferred。例如:

firstFunction().done(secondFunction)

但是 secondFunction 在其范围内使用了 this 关键字,因此当通过 done 调用它时,它无法访问正确的 this 属性。对于更多,这些功能放在不同的文件中。有没有办法用正确的 this 属性 调用 secondFunction

是的,您可以将函数绑定到正确的上下文。

对于 IE9 及更高版本,您可以为此使用本机 Javascript,即 Function.prototype.bind

firstFunction().done(secondFunction.bind(this));

如果出于某种原因你支持 IE8,那么你要么需要对其进行 polyfill(上面链接的 mdn 页面上有一个配方),要么你可以使用 underscore's bind,它应该可用,因为它是必需的通过 backbone.

firstFunction().done(_.bind(secondFunction, this));