JavaScript-函数构造函数无需使用'new'关键字即可工作 [英] JavaScript - Function constructor works without the 'new' keyword

查看:146
本文介绍了JavaScript-函数构造函数无需使用'new'关键字即可工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们都知道,不带 new关键字调用JavaScript构造函数是很糟糕的。
那么为什么这样做?

We all know that it's bad to call a JavaScript constructor function without the 'new' keyword. So why does this:

Function("a", "b", "return a + b")(1, 1); // returns "2"

返回相同的值吗?:

new Function("a", "b", "return a + b")(1, 1); // Also returns "2"

如果省略 new,是否有任何危害(或收益)

And is there any harm (or benefit) in omitting the 'new' key word in this instance?

推荐答案

Function 构造函数创建一个新功能,无论您是否使用 new 调用它。就是这样写的。

The Function constructor creates a new function whether you call it with new or not. That's just how it is written. Constructors can be written that way, if desired.

函数构造函数上的MDN页面


调用函数构造函数作为函数(不使用新的
运算符)与将其作为构造函数调用具有相同的效果。

Invoking the Function constructor as a function (without using the new operator) has the same effect as invoking it as a constructor.

有在 Function 构造函数中使用 new 运算符没有任何害处或益处,甚至没有任何区别。

There is no harm or benefit or even any difference in using or not using the new operator with the Function constructor.

这篇关于JavaScript-函数构造函数无需使用'new'关键字即可工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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