gpt4 book ai didi

javascript - 为什么我的变量在 Underscore.js 每个函数中未定义?

转载 作者:行者123 更新时间:2023-12-03 12:28:05 25 4
gpt4 key购买 nike

这是我的代码:

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 是未定义的。

最佳答案

在 JavaScript 中,函数上下文,称为 this , 作品 rather differently .

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

  • 使用临时变量来存储上下文:
    SetTexts: function (texts) {
    var that = this;
    _.each(texts, function (text) {
    that._textArr[text.Key] = text.Value;
    });
    }
  • 使用第三个参数为 _.each() 传递上下文:
    SetTexts: function (texts) {
    _.each(texts, function (text) {
    this._textArr[text.Key] = text.Value;
    }, this);
    }
  • 关于javascript - 为什么我的变量在 Underscore.js 每个函数中未定义?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13356203/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com