So let\'s say I have a javascript function
function A(){
return function(){
console.log(\'something\');
return new B();
}
}
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".
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
.
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:
prototype
of function A
is examined:
A
is an object, newly created object's prototype
is set to A
's prototype.prototype
is set to the default prototype of Object
.A()
is called, and the result is examined.
new
.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');
return new B();
}
(Note that no_new
and with_new
are equivalent but not identical. They do not refer to the same object: JSFiddle)
function A() {
return function(){
console.log('something');
return new B();
}
}
function B() {
}
var no_new = A();
var with_new = new A();
alert(no_new);
alert(with_new);
var are_they_same = (no_new === with_new);
alert(are_they_same);