【问题标题】:Scope of function called after deffered resolved延迟解析后调用的函数范围
【发布时间】:2015-10-09 09:24:24
【问题描述】:

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

firstFunction().done(secondFunction)

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

【问题讨论】:

  • 一些代码会很好 - 但.bind 可能是你要找的

标签: javascript jquery backbone.js jquery-deferred


【解决方案1】:

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

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

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

如果由于某种原因您支持 IE8,那么您需要对其进行 polyfill(上面链接的 mdn 页面上有一个配方),或者您可以使用 underscore's bind,它应该是可用的,因为它是主干所需要的。

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-04-23
    • 1970-01-01
    • 1970-01-01
    • 2017-01-19
    • 2017-09-06
    • 1970-01-01
    相关资源
    最近更新 更多