我在访问此范围时遇到问题,我如何在 nesed 中应用此范围。
问题是我无法在成功方法中访问 THIS。
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();
最佳答案
使用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); );
关于javascript - 在其他范围内访问它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17321079/