2013-10-09 65 views
1

我有一個在其內部函數中使用jQuery函數的類。 如何引用jQuery回調函數中的成員變量?訪問嵌套函數中的成員變量

見下面的代碼:

var UriParser = function(uri) { 
     this._uri = uri; // let's say its http://example.com 
    }; 

    UriParser.prototype.testAction = function() { 
     $('a').on('click', function(event) { 
      // I need the above this._uri here, 
      // i.e. http://example.com    
     } 
    } 

回答

4

問題是this的事件處理程序內沒有指向的UriParser對象,它指其中被點擊的DOM元素。

一種解決方案是使用封閉可變

UriParser.prototype.testAction = function() { 
    var self = this; 
    $('a').on('click', function (event) { 
     //use self._uri 
    }) 
} 

另一個是使用$.proxy()傳遞一個自定義的執行上下文

UriParser.prototype.testAction = function() { 
    $('a').on('click', $.proxy(function (event) { 
     //use this._uri 
    }, this)) 
}