gpt4 book ai didi

javascript - ES6 模板文字 : How to pass a scope before they are interpreted?

转载 作者:搜寻专家 更新时间:2023-10-31 23:34:44 25 4
gpt4 key购买 nike

我开始使用模板文字来制作错误生成器。

我有工作代码,但我不得不在 constructor 范围内声明可能的错误列表,我对此并不满意。

有没有办法在不评估的情况下复制模板文字,以便我可以在正确的范围内评估它?或者将范围传递给模板文字?

工作error.js:

'use strict';

class Error {
constructor(code) {
const error = {
//...
//API
1001: 'No token',
1002: `${arguments[1]}`,
1003: `${arguments[1]} ! ${arguments[2]}`,
1004: 'Missing data'
//...
};
let i = 0;
this.code = code;
this.error = error[code];
//...
}
}

// export default Error;
module.exports = Error;

像这样调用:

'use strict';
const Error = require('./error.js');

console.log(new Error(1002, 'var'));

我想要的是能够在模块范围内声明const error,或者更好的是,在我需要的它自己的文件中。但是现在这样做会导致 argument 不是 constructor 的参数,而是模块的参数。

最佳答案

字符串字面量被立即评估。它们不能用作稍后格式化的模板(不同于看起来相似的 Python 格式字符串)。

您可以按照 Leonid Beschastny 的建议进行操作,并使用为您进行插值的小函数。

像这样:

const error = {
1001: () => 'No token',
1002: (args) => `${args[1]}`,
1003: (args) => `${args[1]} ! ${args[2]}`,
1004: () => 'Missing data'
};
this.error = error[code](arguments);

关于javascript - ES6 模板文字 : How to pass a scope before they are interpreted?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40235363/

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