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
645 views
in Technique[技术] by (71.8m points)

declaring function with new keyword and self invoke it in javascript

I came across a code that look like this:

 const tempFunc = exp => {
  return new Function(`return ${exp}`)()
 }

first question: is it self invoking the function and return it?. what does tempFunc return exactly?

second question: if we call the function:

let result=tempFunc('3+2')

the result is 5.how does it convert the string and calculate the result?


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

1 Reply

0 votes
by (71.8m points)

When you call tempFunc('3+2') it returns new Function("return 3+2")(), which will create a function (function() { return 3+2 };) and then call that function.

Conversely, if tempFunc looked like this:

const tempFunc = exp => {
  return new Function(`return ${exp}`);
 }

Then it would just return the new function uncalled and you'd have to call it separately: tempFunc('3+2')();

Function Constructor

The function constructor (new Function()) is pretty interesting; you can basically tell it what arguments to expect as the first n arguments and the final argument is the function body. In your example, there are no arguments to our new function, but we could create one that takes arguments:

const tempFunc = num => {
  return new Function('x', `return x + ${num}`)(2);
}

tempFunc(3);
// 5

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...