This question already has answers here:
difference between Function and new Function
                                
                                    (3个答案)
                                
                        
                        
                            When does *not* using new work on built-ins? [duplicate]
                                
                                    (2个答案)
                                
                        
                                5年前关闭。
            
                    
我们都知道,没有'new'关键字的情况下调用JavaScript构造函数很不好。
那么为什么这样做:

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


返回与此相同的值?:

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


在这种情况下,省略“新”关键字是否有任何危害(或利益)?

最佳答案

Function构造函数会创建一个新函数,无论您是否使用new调用它。就是这样写的。如果需要,构造函数可以用这种方式编写。

MDN page on the Function constructor


  将Function构造函数作为一个函数调用(不使用new
  运算符)与调用它作为构造函数具有相同的效果。


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

关于javascript - JavaScript-函数构造函数无需使用'new'关键字即可工作,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/27085657/

10-11 22:45
查看更多