javascript - Array.prototype.map(callback, thisArg),第二个参数被忽略

标签 javascript node.js

我正在使用 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/

相关文章:

带有前导零属性排序的javascript关联数组

javascript - 将子 div 高度限制为父容器高度

node.js - -bash 终端中找不到可执行文件命令

node.js - Electron 需要神秘

javascript - Chrome 分析器上的 "Unsupported non-primitive compare"

javascript - 根据文本长度自动在表格中显示更多/更少的文本

javascript - 谷歌地图标记事件 'dragend' 问题

node.js - 使用 babel 转译时删除 module.exports 声明

javascript - 从 request.files_nodejs 读取内容

node.js - 为什么会出现错误 JwtStrategy requires a secret or key?