In another question, a user pointed out that the new
keyword was dangerous to use and proposed a solution to object creation that did not use new
.
Here is the briefest summary I could make of the two strongest arguments for and against using the new
operator:
new
new
operator can have disastrous
effects if they are incorrectly
invoked as normal functions. A
function's code in such a case will
be executed in the scope where the
function is called, instead of in
the scope of a local object as
intended. This can cause global
variables and properties to get
overwritten with disastrous
consequences.function Func()
,
and then calling Func.prototype
and adding stuff to it so that you
can call new Func()
to construct
your object seems ugly to some
programmers, who would rather use
another style of object inheritance
for architectural and stylistic
reasons.For more on this argument check out Douglas Crockford's great and concise book Javascript: The Good Parts. In fact check it out anyway.
new
new
operator along with
prototypal assignment is fast.See John Resig's post for a simple explanation of this technique, and for a generally deeper explanation of the inheritance model he advocates.