Juri Strumpflohner
Juri Strumpflohner Juri is a full stack developer and tech lead with a special passion for the web and frontend development. He creates online videos for Egghead.io, writes articles on his blog and for tech magazines, speaks at conferences and holds training workshops. Juri is also a recognized Google Developer Expert in Web Technologies

Exploring JavaScript: Scope Pollution when instantiating JavaScript Objects

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){
this.name = first + " " + second;
};

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

document.write(name);
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

document.write(name);
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.
Questions? Thoughts? Hit me up on Twitter
comments powered by Disqus