javascript - 在其他范围内访问它

标签 javascript scope

我在访问此范围时遇到问题,我如何在 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();

http://jsfiddle.net/P6X8L/

最佳答案

使用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/

相关文章:

php - Javascript 等效于 php 的 $object->{$stringvar} = 1 没有 eval()?

javascript - jQuery 变量作用域/调用顺序

javascript - 在 javascript 中,如何使用私有(private)方法向对象添加/执行新方法?

python - Python 与 ML 中的词法作用域

javascript - 访问 "Parent Scope"

javascript - 在loop rivets js中设置其他属性

JavaScript : Prevent showing alert when the url being opened is invalid

javascript - 显示隐藏最近单击的元素

javascript - 使用存储在 txt 文件中的 JSON 输入创建下拉菜单

javascript - 访问函数范围之外的变量但不使其成为全局变量(window.hazaa)?