Setting the anonymous function scope 'this' in jQuery / ajax utility

As noted in this blog post , you can set the scope thisin an anonymous function in Javascript.

Is there a more elegant way to define thisin an anonymous function call on successan AJAX request (i.e. not using that)?

For instance:

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');

Using a call, but still need to specify the scope of the parent that.

success: function(data) {
    (function() {
      this._updateDiv(id, data);
    }).call(that);
}
+2
source share
2 answers

In jQuery 1.4 you have a method $.proxy, you can simply write:

 //...
 bar: function(id) {
    $.ajax({
      url: "someurl",
      success: $.proxy(this, '_updateDiv')
    });
  },
  //...

$.proxy , this, ( ), , , .

bind, ECMAScript Fifth Edition:

//...
  bar: function(id) {
    $.ajax({
      url: "someurl",
      success: function(data) {
        this._updateDiv(id, data);
      }.bind(this)
    });
  },
//...

, JavaScript ES5, 8- :

// The .bind method from Prototype.js 
if (!Function.prototype.bind) { // check if native implementation available
  Function.prototype.bind = function(){ 
    var fn = this, args = Array.prototype.slice.call(arguments),
        object = args.shift(); 
    return function(){ 
      return fn.apply(object, 
        args.concat(Array.prototype.slice.call(arguments))); 
    }; 
  };
}
+6

$.ajax() :

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

CMS .

+6

Source: https://habr.com/ru/post/1762933/


All Articles