Here's what's basically happening when you are using new
, it:
- Creates a new object, let it be
o
.
- Sets the prototype link of
o
to [constructor].prototype
.
- Executes the
[constructor]
with o
as the context object (this
).
- Returns
o
unless the [consructor]
returns a non-primitive value. In that case, that non-primitive value is returned instead of o
. (Added these precisions as suggested by @Esailija).
When you are not using new
, nothing of this happens and the context object is window
, unless the function was invoked on another object. In this case, the context object would be that object.
E.g.
function A() {}
A(); //this points to window
var o = { A: A };
o.A(); //this points to o
Every function
can be a constructor in JavaScript, however you must use the new
keyword in order to get the expected result.
To avoid mistakes, some people will design their function so that forgetting the new
keyword will not be harmful, like below, however there are better alternatives to detect these mistakes, like using code analysis tools like JSHint.
E.g.
function Foo(args) {
if (!(this instanceof Foo)) {
return new Foo(args);
}
//initialization code
}