Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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()?

question from:https://stackoverflow.com/questions/66058075/using-function-context-variables-without-function-arguments

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
458 views
Welcome To Ask or Share your Answers For Others

Please log in or register to answer this question.

Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...