相关疑难解决方法(0)

在jQuery实用程序/ ajax方法中设置'this'的匿名函数范围

本博文中所述,您可以this在Javascript中设置匿名函数的范围.

在AJAX请求this的匿名函数调用中是否有更优雅的方法作用success(即不使用that)?

例如:

var Foo = {

  bar: function(id) {

    var that = this;

    $.ajax({
      url: "www.somedomain.com/ajax_handler",
      success: function(data) {
        that._updateDiv(id, data);
      }
    });

  },

  _updateDiv: function(id, data) {

    $(id).innerHTML = data;

  }

};

var foo = new Foo;
foo.bar('mydiv');
Run Code Online (Sandbox Code Playgroud)

使用调用但仍必须命名父对象范围that.

success: function(data) {
    (function() {
      this._updateDiv(id, data);
    }).call(that);
}
Run Code Online (Sandbox Code Playgroud)

javascript jquery scope anonymous-function

2
推荐指数
2
解决办法
3522
查看次数

标签 统计

anonymous-function ×1

javascript ×1

jquery ×1

scope ×1