2012-11-13 26 views
18

這裏是我的代碼:爲什麼我的變量在Underscore.js中的每個函數內都未定義?

TextClass = function() { 
    this._textArr = {}; 
}; 

TextClass.prototype = { 
    SetTexts: function (texts) { 
     for (var i = 0; i < texts.length; i++) { 
      this._textArr[texts[i].Key] = texts[i].Value; 
     } 
    }, 
    GetText: function (key) { 
     var value = this._textArr[key]; 
     return String.IsNullOrEmpty(value) ? 'N/A' : value; 
    } 
}; 

我使用的Underscore.js庫,並希望這樣定義我的SetTexts功能:

_.each(texts, function (text) { 
    this._textArr[text.Key] = text.Value; 
}); 

但_textArr是不確定的,當我進入循環。

+8

因爲回調裏面的this和外面的不一樣。使用第三個參數'each'來傳遞你想要的回調內容。 – DCoder

回答

33

在JavaScript中,函數上下文,被稱爲this,作品rather differently

您可以通過兩種方式解決這個問題:

  1. 使用一個臨時變量來存儲上下文:

    SetTexts: function (texts) { 
        var that = this; 
        _.each(texts, function (text) { 
        that._textArr[text.Key] = text.Value; 
        }); 
    } 
    
  2. 使用第三個參數_.each()通過上下文:

    SetTexts: function (texts) { 
        _.each(texts, function (text) { 
        this._textArr[text.Key] = text.Value; 
        }, this); 
    } 
    
1

this在JavaScript中的工作方式與您所期望的不同。閱讀這篇文章: http://www.digital-web.com/articles/scope_in_javascript/

短版:

this值更改每次調用一個函數的時間。以固定,設置另一個變量等於this,並說明代替

TextClass = function() { 
    this._textArr = {}; 
}; 

TextClass.prototype = { 
    SetTexts: function (texts) { 
     var that = this; 
     for (var i = 0; i < texts.length; i++) { 
      that._textArr[texts[i].Key] = texts[i].Value; 
     } 
    }, 
    GetText: function (key) { 
     var value = this._textArr[key]; 
     return String.IsNullOrEmpty(value) ? 'N/A' : value; 
    } 
}; 
5

你要通過this作爲上下文_.each調用是這樣的:

_.each(texts, function (text) { 
    this._textArr[text.Key] = text.Value; 
}, this); 

請參閱該文檔爲http://underscorejs.org/#each

+0

工程就像魅力!萬分感謝所有repliers :-) – CJe

0

請注意,您還可以通過其他的事情,「本」。例如,我做類似的事情:

var layerGroupMasterData = [[0],[1,2,3],[4,5],[6,7,8,9],[10]]; 

_.each(layerGroupMasterData,function(layerGroup,groupNum){ 
    _.each(layerGroup, function (layer, i) { 
      doSomethingThatComparesOneThingWithTheOverallGroup(layerGroupMasterData,layer); 
    },layerGroups); 
},layerGroupMasterData); 
相關問題