Function vs new Function [duplicate]

问题描述 投票:0回答:1

[在关键字Function前面使用new和不使用它来调用Function构造函数之间有什么区别?

 var result = Function('a', 'b', 'return a + b');
 var myResult = new Function('a','b', 'return a + b');

我知道新的运算符,并且它:创建一个空白的纯JavaScript对象将这个对象链接(设置其构造函数)到另一个对象;....

但是在这种情况下使用构造函数很明智

 function Car(make, model, year) {
    this.make = make;
    this.model = model;
    this.year = year;
}

 const car1 = new Car('Eagle', 'Talon TSi', 1993);

我知道在这种情况下每次都会创建新的汽车实例。

但是在上面的示例中,结果和myResult有什么区别?请给我更好的解释。

javascript function constructor new-operator
1个回答
0
投票
result = function(){};

将对匿名函数的引用放入结果中。结果指向一个函数。

myResult = new function(){};

将对匿名构造函数的新构造实例的引用放入myResult。 myResult指向一个对象。


0
投票

没有区别。函数构造函数看起来(或多或少)如下:

 function Function(...args) {
   if(!(this instance of Function)) {
      return new Function(...args);
   }
   // ... further magic
 }

因此,无论您调用还是构造Function,都会创建并返回一个新的函数对象,就像构造Car时创建汽车对象的方式一样。

© www.soinside.com 2019 - 2024. All rights reserved.