我正在使用 Node.js 编写一个小游戏,我希望它能以两种不同的语言提供。
为了显示不同游戏模式的翻译列表及其各自的描述,我正在使用 Array.prototype.map(callback, thisArg)
,但看起来 Node 忽略了 thisArg
参数:
sendMessage(translated[channel.id].modeList + modes.filter(a => {
if (typeof a === "string")
return true;
return false;
}).map(translated.modeDesc, translated[channel.id]).join("\n"));
翻译
:
const translated = {
"chooseLang" : "Choose a language",
"invalidOption" : "Invalid option",
"modeDesc" : mode => {return mode + " : " + "<" + modes[0][mode].join("|") + ">\n = " + this.modeDescs[mode];},
"(channel id)" : global.en
};
global.en
:
const en = {
"modeList" : "Here is a list of available gamemodes :",
"modeDescs" : {
"mode" : "description"
}
};
看起来 Node 正在尝试使用 translated.modeDescs
,它不存在,而不是 translated[channel.id].modeDescs
(global. en.modeDescs
) :
TypeError: Cannot read property 'mode' of undefined
at Object.ruleDesc (/home/algorythmis/Documents/Game/main.js:89:111)
at Array.map (native)
...
那么,是 Node 真的忽略了 thisArg
还是我只是用错了方式?我可以做些什么来获得我想要的行为?
提前致谢。
最佳答案
使用 arrow function 时,词法作用域被保留,所以this
指的是translated
对象定义的上下文,而不是保存该对象的实际对象对函数的引用。
尝试使用常规函数:
"modeDesc" : function(mode) {return mode + " : " + "<" + modes[0][mode].join("|") + ">\n = " + this.modeDescs[mode];}
或者使用调用
显式设置上下文:
var data = translated[channel.id].modeList + modes.filter(a => { ... });
data = Array.prototype.map.call(translated, translated.modeDesc);
sendMessage(data);
参见 MDN
关于javascript - Array.prototype.map(callback, thisArg),第二个参数被忽略,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42053249/