I’ve seen these two approaches for creating js objects with closures, but wasn’t sure if there were any advantages for using one approach over another:
1.) Using new
var myObject = new function() {
// ...
this.foo = 'bar';
};
2.) Using self-executing anonymous
var myObject = (function() {
// ...
return {
foo: 'bar'
};
} ());
I’ve read some about approach 1 having some overhead for needing to allocate this, but I wasn’t sure if that claim was being compared to something like approach 2, or in comparison to a non-returning self-executing anonymous function.
Personally I think the first syntax looks more maintainable, but that might just be personal preference.
I ended up doing some further searching and came across this somewhere along the way comparing several methods of instantiation:
http://jsperf.com/new-vs-literal/4
Seems using the
new function() {};pattern is significantly slower