Exploring JavaScript: Scope Pollution when instantiating JavaScript Objects

John Resig has written a very interesting article (I'm not able to find just now) on how the current scope might get polluted if you're accidentally invoking a function intended as an object constructor function without using the "new" keyword in front. Here's a simple example that illustrates the issue.

Basically consider you have the following, extremely simple code:
var Person = function(first, second){
this.name = first + " " + second;

//using it somewhere
var name = "Juri";
var aPerson = new Person("Peter", "Oberhofer"); //invoking the constructor function

Now as expected you'd assume "Juri" to be printed as you don't do anything else than printing the current variable name.

Now what happens if you forget to use the "new" keyword like
var name="Juri";
var aPerson = Person("Peter", "Oberhofer"); //attention, no "new" keyword

What would be the result? Can you guess it? It would be: Peter Oberhofer. Strange, right? The problem is that given the fact you didn't specify the "new" keyword the function Person wrote on the global namespace when executing this.name = .... The declaration of var name = "Juri" is in this case on the global namespace as well, hence without specifying the new keyword you overwrite the previous declaration, resulting in Peter Oberhofer to be printed out.

You can check out a live sample here: http://jsbin.com/ozawep/4/edit#javascript,live.



Your ad here?