Setting anonymous function scope of 'this'

2019-07-22 03:57发布

问题:

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

Is there a more elegant way of scoping this in the anonymous function call on success of the AJAX request (i.e. not using that)?

For example:

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 call but still have to name the parent object scope that.

success: function(data) {
    (function() {
      this._updateDiv(id, data);
    }).call(that);
}

回答1:

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

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

$.proxy takes an object, that will be used as the this value and it can take either a string (a member of that object) or a function, and it will return a new function that will always have a particular scope.

Another alternative is the bind function, now part of the ECMAScript Fifth Edition standard is the best:

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

This function will be available natively soon, when JavaScript engines fully implement the ES5 standard, for now, you can use the following 8-line long implementation:

// 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))); 
    }; 
  };
}


回答2:

The $.ajax() function provides a concise means of doing this already in the form of the context parameter:

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

Though the techniques CMS outlines are more suitable for general use.