Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
464 views
in Technique[技术] by (71.8m points)

javascript - Using function context/variables without function arguments

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

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

Please log in or register to reply this article.

OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...