Skip to content Skip to sidebar Skip to footer

Is Calling A Function That Returns A Function With New Different Than Just Invoking It Normally?

So let's say I have a javascript function function A(){ return function(){ console.log('something'); return new B(); } } Is calling this using new A(); any

Solution 1:

Since that function has an explicit return and makes no use of this, there is no difference in the result of running it with or without new.

Solution 2:

When you call the function without "new", what is it that you suspect "this" is pointing to? It'll be "window." Updating that is slower than updating the freshly-built new object you'll be using when you invoke it with "new".

Solution 3:

Others have given answers about the result (is the use of new equivalent to not using it or not?), but let me explain why following two results are equivalent:

var no_new = A();
var with_new = new A();

The relevant part of the ECMAScript is section 13.2.2 (I will omit and simplify some information and adapt the contents of that section to suit this answer). This is what happens when new A() is executed:

  1. A new object is created.
  2. The prototype of function A is examined:
    1. If the prototype of A is an object, newly created object's prototype is set to A's prototype.
    2. If not, newly created object's prototype is set to the default prototype of Object.
  3. Function A() is called, and the result is examined.
    1. If the result is an object, the result will be the return value of new.
    2. Else the newly created object will be the return value of new.

In your case, the execution will take the path 3.1, aka new operator will return a reference to the inner anonymous function, same as the function call without new.

So, both variables no_new and with_new will have a reference to a function in the following form:

function () {
    console.log('something');
    returnnewB();
}

(Note that no_new and with_new are equivalent but not identical. They do not refer to the same object: JSFiddle)

functionA() {
    returnfunction(){
        console.log('something');
        returnnewB();
    }
}

functionB() {
}

var no_new = A();
var with_new = newA();

alert(no_new);
alert(with_new);

var are_they_same = (no_new === with_new);
alert(are_they_same);

Post a Comment for "Is Calling A Function That Returns A Function With New Different Than Just Invoking It Normally?"