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
. I didn't believe that was true, mostly because I've used Prototype, Scriptaculous and other excellent JavaScript libraries, and everyone of them used the new
keyword.
In spite of that, yesterday I was watching Douglas Crockford's talk at YUI theater and he said the exactly same thing, that he didn't use the new
keyword anymore in his code (Crockford on JavaScript - Act III: Function the Ultimate - 50:23 minutes).
Is it 'bad' to use the new
keyword? What are the advantages and disadvantages of using it?
Here is the briefest summary I could make of the two strongest arguments for and against using the
new
operator:Argument against
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 callingFunc.prototype
and adding stuff to it so that you can callnew 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.
Argument in favor of
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.
Crockford has done a lot to popularize good JavaScript techniques. His opinionated stance on key elements of the language have sparked many useful discussions. That said, there are far too many people that take each proclamation of "bad" or "harmful" as gospel, refusing to look beyond one man's opinion. It can be a bit frustrating at times.
Use of the functionality provided by the
new
keyword has several advantages over building each object from scratch:prototype
and usenew
to stamp out new objects. Not only is this faster (no code needed for each and every method on the prototype), it avoids ballooning each object with separate properties for each method. On slower machines (or especially, slower JS interpreters) when many objects are being created this can mean a significant savings in time and memory.And yes,
new
has one crucial disadvantage, ably described by other answers: if you forget to use it, your code will break without warning. Fortunately, that disadvantage is easily mitigated - simply add a bit of code to the function itself:Now you can have the advantages of
new
without having to worry about problems caused by accidentally misuse. You could even add an assertion to the check if the thought of broken code silently working bothers you. Or, as some commented, use the check to introduce a runtime exception:(Note that this snippet is able to avoid hard-coding the constructor function name, as unlike the previous example it has no need to actually instantiate the object - therefore, it can be copied into each target function without modification.)
John Resig goes into detail on this technique in his Simple "Class" Instantiation post, as well as including a means of building this behavior into your "classes" by default. Definitely worth a read... as is his upcoming book, Secrets of the JavaScript Ninja, which finds hidden gold in this and many other "harmful" features of the JavaScript language (the chapter on
with
is especially enlightening for those of us who initially dismissed this much-maligned feature as a gimmick).I am newbie to Javascript so maybe I am just not too experienced in providing a good view point to this. Yet I want to share my view on this "new" thing.
I have come from the C# world where using the keyword "new" is so natural that it is the factory design pattern that looks weird to me.
When I first code in Javascript, I don't realize that there is the "new" keyword and code like the one in YUI pattern and it doesn't take me long to run into disaster. I lose track of what a particular line is supposed to be doing when looking back the code I've written. More chaotic is that my mind can't really transit between object instances boundaries when I am "dry-running" the code.
Then, I found the "new" keyword which to me, it "separate" things. With the new keyword, it creates things. Without the new keyword, I know I won't confuse it with creating things unless the function I am invoking gives me strong clues of that.
For instance, with
var bar=foo();
I have no clues as what bar could possibly be.... Is it a return value or is it a newly created object? But withvar bar = new foo();
I know for sure bar is an object.I think "new" adds clarity to the code. And clarity is worth everything. Good to know there are pitfalls, but avoiding them by avoiding clarity doesn't seem like the way for me.
Case 1:
new
isn't required and should be avoidedCase 2:
new
is required, otherwise you'll get an errorI have just read some parts of his Crockfords book "Javascript: The Good Parts". I get the feeling that he considers everything that ever has bitten him as harmful:
About switch fall through:
About ++ and --
About new:
There are more, but I hope you get the picture.
My answer to your question: No, it's not harmful. but if you forget to use it when you should you could have some problems. If you are developing in a good environment you notice that.
Update
About a year after this answer was written the 5th edition of ECMAScript was released, with support for strict mode. In strict mode,
this
is no longer bound to the global object but toundefined
.