c4i*_*4il 11 javascript function
今天我读过我们有一种通过Function构造函数声明函数的方法.但我从未见过真正使用Function构造函数的实际实现.所以我想问一下,有什么情况我们可以通过使用Function构造函数而不是使用function()声明来获益吗?两者之间隐藏的差异是什么?(如果有的话)
函数构造函数
var func = new Function("x", "y", "return x*y;"); // pass the context by String
Run Code Online (Sandbox Code Playgroud)
功能():
var func = function(x, y){ return x*y; }
Run Code Online (Sandbox Code Playgroud)
谢谢
Cri*_*hez 10
Function构造函数是一种形式eval,通常应该避免(它很慢并且被认为是不安全的).除非要从动态组件构造函数,否则在构建函数语句中使用Function构造函数确实没有任何好处,这是非常罕见的.这种形式有合法的用途,但是大多数时候它被不必要地使用,这就是为什么它被低估并且通常避免的原因.
此外,使用函数构造函数创建的函数不会保留对它们在(闭包)中定义的环境的引用.执行时,它们将直接从全局范围中提取这些变量.
var f, a;
(function () {
var a = 123;
f = new Function("return a");
})();
f(); //undefined
a = "global"
f(); // "global"
Run Code Online (Sandbox Code Playgroud)
常规函数确实引用了它们所定义的环境:
var f;
(function () {
var a = 123;
f = function () { return a; }
})();
f(); //123
Run Code Online (Sandbox Code Playgroud)