为什么我的变量在Underscore.js中的每个函数都未定义? [英] Why is my variable undefined inside the Underscore.js each function?

查看:90
本文介绍了为什么我的变量在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函数:

I'm using the Underscore.js library and would like to define my SetTexts function like this:

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

但是当我进入循环时_textArr是未定义的。

but _textArr is undefined when I get into the loop.

推荐答案

在JavaScript中,函数上下文(称为 this )工作相当不同

In JavaScript, the function context, known as this, works rather differently.

您可以通过两种方式解决此问题:

You can solve this in two ways:


  1. 使用临时变量存储上下文:

  1. Use a temporary variable to store the context:

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


  • 使用第三个参数 _。each() 传递上下文:

  • Use the third parameter to _.each() to pass the context:

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


  • 这篇关于为什么我的变量在Underscore.js中的每个函数都未定义?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆