I'm trying to implement my own template literals functionality (in educational purposes), but I can't understand how it works.
My idea is to extend String.prototype with function, that will eval every ${} sequence inside the string. The problem is my new function don't know context (variables inside the string). Here's how I think it should work:
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()
}
This will cause Uncaught ReferenceError: a is not defined since a and b belong to some_function(), not smart_eval(). Is there any elegant way to solve this without using function arguments or .call() / .apply()?