2013-06-26 123 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