【发布时间】:2021-05-09 11:43:10
【问题描述】:
我正在尝试实现自己的 template literals 功能(出于教育目的),但我不明白它是如何工作的。
我的想法是用函数扩展String.prototype,这将eval 字符串内的每个${} 序列。问题是我的新函数不知道上下文(字符串中的变量)。以下是我认为它应该如何工作:
String.prototype.smart_eval = function() { /* find all ${} and eval them */ }
function some_function() {
let a = 1;
let b = 2;
return 'A is ${a}, B is ${b}, the sum is ${a + b}'.smart_eval()
}
这将导致Uncaught ReferenceError: a is not defined,因为a 和b 属于some_function(),而不是smart_eval()。有没有不使用函数参数或.call() / .apply() 的优雅方法来解决这个问题?
【问题讨论】:
标签: javascript eval template-literals