19

これが私のコードです:

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 は未定義です。

4

4 に答える 4

38

JavaScript では、 として知られる関数コンテキストのthis動作はかなり異なります。

これは、次の 2 つの方法で解決できます。

  1. 一時変数を使用してコンテキストを保存します。

    SetTexts: function (texts) {
      var that = this;
      _.each(texts, function (text) {
        that._textArr[text.Key] = text.Value;
      });
    }
    
  2. 3 番目のパラメーターを使用し_.each()てコンテキストを渡します。

    SetTexts: function (texts) {
      _.each(texts, function (text) {
        this._textArr[text.Key] = text.Value;
      }, this);
    }
    
于 2012-11-13T06:13:40.560 に答える
6

次のように呼び出しのthisコンテキストとして渡す必要があります。_.each

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

http://underscorejs.org/#eachのドキュメントを参照してください

于 2012-11-13T06:13:56.760 に答える
1

this in javascript does not work the same way as you would expect. read this article: http://www.digital-web.com/articles/scope_in_javascript/

short version:

the value of this changes every time you call a function. to fix, set another variable equal to this and reference that instead

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;
    }
};
于 2012-11-13T06:09:28.270 に答える
0

「this」以外のものも渡すことができることに注意してください。たとえば、私は次のようなことをします:

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);
于 2014-05-23T16:10:05.743 に答える