2013-06-26 131 views
1

我遇到了訪問此範圍的問題,我如何將這個範圍應用於neseted。在其他範圍內訪問此

問題是我沒有成功的方法訪問這個。

var Module = { 
    els: { 
     body: $('body') 
    }, 

    success: function(result) { 
     // Body is now undefined, no access to this 
     console.log(result, this.els.body); 
     // Access only via Module, this should be end result 

     Module.els.body.html(result) 
    }, 

    init: function() { 
     $.get('/echo/jsonp', this.success); 
    } 

}; 

Module.init(); 

http://jsfiddle.net/P6X8L/

回答

4

使用jQuery,您可以使用$.proxy(function, context)

$.get('/echo/jsonp', $.proxy(this.success, this); 

沒有jQuery的,你可以使用一個封閉

var myContext = this; 
$.get('/echo/jsonp', function(X) { myContext.success(X);); 

var myContext = this; 
$.get('/echo/jsonp', function() { myContext.success.apply(myContext, arguments);); 
+0

是的,我已經忘了在jQuery中,我接受這個答案,但除了使用庫之外,有沒有解決方案? –

+0

@jurka你也可以使用'Function.prototype.bind':https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind – Ian

+0

@Ian,大腦不工作,忘了那個。注意:如果您使用綁定並需要支持IE8,則需要使用polyfill。 – epascarello