2014-08-31 37 views
0

我有一个javascript命名空间的问题。从ajax回调函数调用方法的更优雅的方法

我想从ajax回调函数调用secondMethod,但我不知道如何获取它的引用。 我已经这样做了。但这个参数的变量对我来说似乎很尴尬。整个建筑难以阅读。

因此,我在那里寻求帮助,并回答如何更好地改写它。

var testObject = new TestObject(); 
testObject.firstMethod("hello world!"); 

function TestObject() { 
    var thisReference = this; 

    this.firstMethod = function(firstParam) { 
     ajaxFunc(firstParam, function(ajaxResult) { 
      thisReference.secondMethod(ajaxResult); 
     }); 
    }; 

    this.secondMethod = function(secondParam) { 
     alert("secondMethod " + secondParam); 
    }; 

} 

function ajaxFunc(hello, callBack) { 
    callBack(hello); 
} 

非常感谢。

Ondra

回答

0

喜欢的东西,你在做什么,是做的常用方法。使用:

var that = this; 

或:

var self = this; 

是常见的名字,让您的原有范围的保持。

另一种选择(我更喜欢)是将this对象绑定到您调用的方法,以便您可以在回调中访问它。这看起来像这样:

this.firstMethod = function(firstParam) { 
    ajaxFunc(firstParam, function(ajaxResult) { 
    this.secondMethod(ajaxResult); 
    }.bind(this)); 
}; 

希望有所帮助。

+0

相反,使用'ajaxFunc(firstParam,this.secondMethod.bind(this))' – Bergi 2014-08-31 16:15:58

+0

感谢您快速回答Antiga。绑定()看起来不错。 Bergi:谢谢。但是我不能因为在调用secondMethod之前更多地使用代码。它只是简化的代码。 – 2014-08-31 16:33:56