簡體   English   中英

在jQuery實用程序/ ajax方法中設置'this'的匿名函數范圍

[英]Setting anonymous function scope of 'this' in jQuery utility / ajax methods

正如指出的這篇博客 ,你可以設置的范圍this在Javascript中的匿名函數。

在AJAX請求success的匿名函數調用中是否有更優雅的方法來確定this (即不使用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');

使用電話,但還是要命名父對象范圍that

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

在jQuery 1.4中你有$.proxy方法,你可以簡單地寫:

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

$.proxy接受一個對象,該對象將用作this值,它可以接受字符串(該對象的成員)或函數,它將返回一個始終具有特定范圍的新函數。

另一種選擇是bind功能,現在ECMAScript第五版標准的一部分是最好的:

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

$.ajax()函數以context參數的形式提供了一種簡潔的方法:

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

雖然CMS概述的技術更適合一般用途。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM