javascript - 如何正确引用 "this"?

标签 javascript jquery

<分区>

假设我有以下内容:

var object = {
    myfunc: function() {
        $.ajax({
           url: url,
           format: format,
           success: function() {

           console.log(this) // This refers to the ajax call and not "object"

                $.ajax({
                  url: url,
                  format: format,
                  success: function() {
                    console.log(this) // this refers to nested ajax call and not "object"
                  }
                });


           }
        });
    }
}

如何让“this”引用“object”而不是 ajax 调用?

最佳答案

使用$.proxy()将自定义上下文传递给回调函数

var object = {
    myvar : "hello",
    myfunc : function() {
        $.ajax({
            url : url,
            format : format,
            success : $.proxy(function() {

                console.log(this) // This refers to the ajax
                // call and
                // not "object"

                $.ajax({
                    url : url,
                    format : format,
                    success : function() {
                        console.log(this) // this
                        // refers to
                        // nested ajax call
                        // and not "object"
                    }
                });

            }, this)
        });
    }
}

关于javascript - 如何正确引用 "this"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16215994/

相关文章:

javascript - d3 v4 为什么我无法使 x 轴和条形对齐?

javascript - 从 img 标签获取背景图像 url 并使用该 url 创建新的 img 标签

php - Codeigniter Twitter 风格流和 Ajax

javascript - 如何在 Bootstrap DataTable 中创建超链接或可点击单元格?

javascript - 元素可见后触发的事件

javascript - Lodash reduce with includes 或 orderBy iteratee 用例

javascript - 将变量从 AJAX 传递到 PHP

javascript - 如何在javascript中对整数进行四舍五入

javascript - on() 和 off(),on() 立即触发,但我希望它像绑定(bind)或实时一样为 "act",这里出了什么问题?

javascript - 获取选择框的 html 并附加到另一个 div 中