What is this and why use new?
Posted: April 28, 2013 Filed under: JavaScript | Tags: constructor, javascript, new Leave a commentGiven the function.
var foo = function(name) {this.name = name; return this;}
This code may not do what one might think it does.
var a = foo("a"); a.name;
var b = foo("b"); b.name;
a.name;
You can kind of see why by checking out what these return.
foo("a");
new foo("a");
This however works as one might expect.
var a = new foo("a"); a.name;
var b = new foo("b"); b.name;
a.name;