Exploring JavaScript: Scope Pollution when instantiating JavaScript Objects
2 min read
2 min read
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){Now as expected you'd assume "Juri" to be printed as you don't do anything else than printing the current variable
this.name = first + " " + second;
};
//using it somewhere
var name = "Juri";
var aPerson = new Person("Peter", "Oberhofer"); //invoking the constructor function
document.write(name);
name
.var name="Juri";What would be the result? Can you guess it? It would be:
var aPerson = Person("Peter", "Oberhofer"); //attention, no "new" keyword
document.write(name);
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.