0

What si difference between calling Function constructor with new and without it in front of keyword Function.

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

I know about new operator and that it: Create a blank, plain JavaScript object Links (sets the constructor of) this object to another object; ....

But that is make sanse in this situation with constructor function

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

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

I know that in this situation each time new car instance will be crated.

But in above example what is difference between result and myResult? Please give me a little bit better explanation.

Predrag Davidovic
  • 1,411
  • 1
  • 17
  • 20

2 Answers2

0

There is no difference. The function constructor looks (more or less) like this:

 function Function(...args) {
   if(!(this instance of Function)) {
      return new Function(...args); // your first call ends up here, so it's like your second
   }
   // ... further magic
 }

So no matter wether you call or construct Function, a new function object gets created and returned, the same way a car object gets created when you contruct Car.

Jonas Wilms
  • 132,000
  • 20
  • 149
  • 151
  • i tried to create another function ('Function1') like Function constructor, it wont behave same. Even as you mentioned that first call ends after 'return new Function(...args);' , it wont ends here. This is what i am trying to do; function Function4(...args) { if(!(this instanceof Function)) { return new Function4(...args); // your first call ends up here, so it's like your second } // ... further magic return 12; } i am expecting new Function4() // return 12 Function4 // return 12 – Suraj Bande Nov 26 '20 at 14:51
-1
result = function(){};

Places a reference to an anonymous function into result. result points to a function.

myResult = new function(){};

Places a reference to a newly constructed instance of an anonymous constructor function into myResult. myResult points to an object.

Rithik Banerjee
  • 447
  • 4
  • 16