【问题标题】:JavaScript OOP scope of visibiltyJavaScript OOP 可见范围
【发布时间】:2014-04-11 17:08:09
【问题描述】:

我的代码如下所示:

function A() {
    this.AFunction = function() {
        var b = new B();
        b.BFunction();
    }
}

function B() {
    this.BFunction = function() {
         // some code
         $.ajax({ url: url
             success: BSuccess,
             // and so on
         })
    }

    this.BSuccess = function() {
         // some code
         this.anotherBFunc();
    }

    this.anotherBFunc = function() {
         // some code
    }
}

a = new A();
a.AFunction();

它在调用另一个BFunc 时失败。请有人帮我理解为什么会这样吗?

【问题讨论】:

标签: javascript ajax oop


【解决方案1】:

要保持范围,您可以使用jQuery's proxy

success: $.proxy(this.BSuccess,this),

或者使用现代浏览器,您可以使用bind

success: this.BSuccess.bind(this),

【讨论】:

  • “现代”是指“任何人实际使用的任何浏览器”kangax.github.io/es5-compat-table/#Function.prototype.bind :)
  • 恐怕人们还在使用 IE8,而且它不现代。
  • 仅估计全球互联网的 10%,有一点……theie8countdown.com
  • 全球 !== 公司的用户群。
  • 好吧,你赢了:Internet Explorer 8 前景广阔,值得花钱无限期地支持。成本:收益分析不仅非常支持仅针对浏览器,而且我们都应该仅凭该软件的实力购买微软股票。 :P
猜你喜欢
  • 1970-01-01
  • 2012-09-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-08-24
  • 2014-04-05
  • 2017-10-07
相关资源
最近更新 更多