我正在寻找一种在函数中使用变量中的模板字符串的方法。
这是一个工作示例(不是变量)
let f = function () {
return `Hello ${this.name}!`
}
f.bind({
name: 'Stackoverflow-User'
})(); // Hello Stackoverflow-User!
这是不起作用的示例(在变量中)
let s = `Hello ${this.name}!`;
let f = function () {
return s;
}
f.bind({
name: 'Stackoverflow-User'
})(); // Hello undefined!
最佳答案
这个:
let f = function () {
return `Hello ${this.name}!`
}
编译成这样:
let f = function () {
return "Hello " + this.name.toString() + "!";
}
只要 f
作为正确对象的方法被调用,它就会起作用。
每次调用函数时都会评估表达式。
在第二种情况下:
var s = "Hello " + this.name.toString() + "!";
let f = function () {
return s;
}
那个 s
仅在加载时获取其值一次,并且 this
错误。
让它以这种方式工作的唯一方法是从中生成函数:
let s = new Function("return `Hello ${this.name}!`;");
并将其用作:
let f = function () {
return s.call(this);
}
有点奇怪,但可以用。
关于javascript - 使用模板字符串 (ES6) 作为函数中的返回变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35493943/