JavaScript OOP可见性范围

时间:2014-04-11 17:08:10

标签: javascript ajax oop

我的代码如下所示:

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();

它在调用anotherBFunc时失败了。可以请一些人帮我理解为什么会发生这种情况?

1 个答案:

答案 0 :(得分:1)

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

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

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

success: this.BSuccess.bind(this),