我是 JS 的新手。 现在我在一本书上读到了这段代码。
var sayMessage = new Function("message", "console.log(message);");
我的问题是这个函数中的 {}
在哪里。
我的意思是我们如何在需要参数的地方编写 message", "console.log(message);
?
谢谢。
最佳答案
JavaScript Function
构造函数可用于从字符串定义函数。构造函数将评估作为最后一个参数传递的字符串作为函数体。
Function objects created with the Function constructor are parsed when the function is created. This is less efficient than declaring a function with a function expression or function statement and calling it within your code, because such functions are parsed with the rest of the code.
来自documentation .
<小时/>这意味着这个声明:
var sayMessage = new Function("message", "console.log(message);");
将被计算为以下表达式:
var sayMessage = function (message) {
console.log(message);
};
您可以看到参数 message
和 console.log(message)
如何从一个映射到另一个。
一开始您想要这样做的原因很少,而且在惯用的 JavaScript 中也很少见。
关于javascript - 函数中的参数包含表达式吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33274192/