Is Calling A Function That Returns A Function With New Different Than Just Invoking It Normally?
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:
- A new object is created.
- The
prototypeof functionAis examined:- If the prototype of
Ais an object, newly created object'sprototypeis set toA's prototype. - If not, newly created object's
prototypeis set to the default prototype ofObject.
- If the prototype of
- Function
A()is called, and the result is examined.- If the result is an object, the result will be the return value of
new. - Else the newly created object will be the return value of
new.
- If the result is an object, the result will be the return value of
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?"