Saturday, February 5, 2011

what does "new" do in JavaScript

Today, a colleague asked about exactly what is the difference between using "new" and calling the function directly. Only thing I can think of is the meaning for "this" inside the function. With "new", this means the object being created, but without "new", this means the global object, either window or something else. And I am also not clear what exactly happens behind the scene.

So, did some search and found some good readings that explains this topic fairly clearly. Lots of related answers from Stack Overflow is also quite helpful:
Here is a good article that tests your understanding of "new" keyword ;-)

Now, whether or not you should use "new" is another question:

Using "new" to instantiate a class has both pros (great performance) and cons (can cause nightmare if you forget to use new). Many people including Douglas Crockford discourages the use of new. A module pattern is a more preferable way. John Resig also has a simple solution to avoid using new directly without much performance sacrifice.

No comments:

Post a Comment