I have this piece of code:
function Test() {
var i=0;
return {
foo : function() { console.log(++i); },
bar : function(a) { i=i+a;console.log(i)}
}
}
var test1 = Test();
var test2 = new Test();
test1 and test2 looks the same, but my question is if there is anything different between them?
newis good for instantiating from a constructor function. That basically means, a new object is formed which then contains all data that is referenced viathiswithin the constructor.Without using
new,thiswould reference the global object and clobber the global namespace (ES3) or it would beundefined(ES5 strict).In your particular snippet here, it doesn’t matter because you’re returning a new object nonetheless from
Test(). That will always be used and assigned totest1andtest2.