函数构造函数与函数语句 [英] Function constructor vs function statement

查看:145
本文介绍了函数构造函数与函数语句的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

今天我读过,我们有一种方法可以通过函数构造函数来声明函数 。但是我从来没有见过使用 Function 构造函数的实际实现。所以我想问一下,是否有任何情况可以通过使用 Function 构造函数而不是使用 function()声明?什么是两者之间的隐藏差异?(如果有的话)

函数构造函数

  var func = new函数(x,y,return x * y;); //通过字符串传递上下文

function():

  var func = function(x,y){return x * y; } 

谢谢

解决方案

Function构造函数是 eval 的形式,通常应该避免这种情况(它很慢并且被认为是不安全的)。除非你想从动态组件中构造一个函数,这是非常罕见的,否则使用函数构造函数通过内置函数语句确实没有任何好处。这种形式有合理的用途,然而大多数时候它被不必要地使用,这就是为什么它被忽视并且通常被避免。

此外,使用函数构造函数创建的函数不会保留对它们定义的环境的引用(闭包)。在执行时,它们将直接从全局范围中提取这些变量。

  var f,a; 
(function(){
var a = 123;
f = new Function(return a);
})();

f(); //未定义

a =全局
f(); //全局

常规函数确实引用了它们定义的环境:

  var f; 
(function(){
var a = 123;
f = function(){return a;}
})();
f(); // 123


today I've read we have a way of declaring the function by Function constructor. But I never seen the actual implementation that uses Function constructor in real. So I would like to ask, are there any circumstances that we can get benefit by using Function constructor as opposed to using function() declaration? And what are the hidden differences of between?(if there is any)

Function Constructor

var func = new Function("x", "y", "return x*y;"); // pass the context by String

function():

var func = function(x, y){ return x*y; }

Thanks

解决方案

The Function constructor is a form of eval, which should generally be avoided (it's slow and considered insecure). There is really no benefit to using the Function constructor over the built in function statement unless you want to construct a function from dynamic components, which is pretty rare. There are legitimate uses for this form, however most of the time it's used unnecessarily which is why it's looked down upon and generally avoided.

Also, functions created with the function constructor will not keep a reference to the environment they were defined in (the closure). When executed, they will pull those variables directly from the global scope.

var f, a;
(function () {
   var a = 123;
   f = new Function("return a");
})();

f(); //undefined

a = "global"
f(); // "global"

Whereas regular functions do keep a reference to the environment in which they were defined:

var f;
(function () {
   var a = 123;
   f = function () { return a; }
})();
f(); //123

这篇关于函数构造函数与函数语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆