In Javascript, there’s an interesting operator called new
. In JavaScript: The Good Parts, new
is listed as a not recommended operator. Let’s explore the usage of new
.
Consider the following code:
function test() {
var foo1 = new function () {
this.i = 1;
}
var foo2 = function () {
this.i = 2;
}
M.dis(foo1.i); // 1
M.dis(foo2.i); // undefined
M.dis(this.i); // undefined
foo2();
M.dis(foo2.i); // undefined
M.dis(this.i); // 2
M.dis(foo1.prototype); // undefined
M.dis(foo2.prototype); // [object Object]
}
In the code, M.dis()
is equivalent to document.writeln()
.
The above code clearly illustrates the difference between using and not using the new
operator.
Below are my understandings based on the results of using and not using the new
operator.
Functions with the
new
operator are executed immediately. Withoutnew
, functions execute when called.foo1
is executed upon definition, hencefoo1.i = 1
is outputted. Sincefoo2
is not executed upon definition, its output isundefined
. The definitionvar foo2 = function () {}
is equivalent tofunction foo2 () {}
.With the
new
operator,this
is bound to the function itself.This is straightforward. In the definition of
foo1
, it is executed immediately, so you can think offoo1
as the execution context of the function, andthis
naturally binds tofoo1
, i.e., the function itself. Therefore,foo1.i
outputs a result. Withoutnew
, the function is not executed immediately, and when the function (i.e.,foo2
) is called, the execution context is thetest()
function. Thus,this.i
intest()
outputs a result. Theundefined
result forfoo2.i
is understandable since it’s akin to executingfoo2().i
, which is not a valid usage.Prototype differences between using and not using the
new
operator.When using
new
, a constructor function is instantiated, so its prototype is naturallyundefined
.
Withoutnew
,foo2
is just a function, and its prototype is the function’s prototype.
For more on prototype issues with and withoutnew
, refer to an article by the Taobao UED team:http://ued.taobao.com/blog/2007/05/15/ Do You Really Know How to Write JavaScript?
update1:
The exploration of the new
operator is currently limited to new function
. As for the differences between new Array()
and []
, as well as new Object()
and {}
, I believe the differences are not as significant as between new function
and function. However, some argue there are differences between new Array()
and []
(see comments in “Do You Really Know How to Write JavaScript?”).
update2:
There is a significant difference between new Array()
and array literals. For example, to define an array with a single element 3
, consider the code:
var a = new Array(3); // This defines an array with a length of 3
var b = [3]; // Correct!
Clearly, only literals can define an array with a single element.