Closure Object Creation: What are the advantages/disadvantages of these two approaches?
I've seen these two approaches for creating js objects with closure开发者_StackOverflow中文版s, 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.
The first statement delivers a full fledged Object instance - albeit the only possible instance, because the constructor can be used once - the second delivers an object literal. In this case I don't see much difference, both can be called 'one time instance patterns'. The only advantage the first pattern has (for me) is that my editor (KomodoEdit 6.1) can use intellisense for it (it recognizes myObject and 'knows' it's properties). Maybe another advantage of the first pattern could be that it's possible to define prototype methods for it (if you name the anonymous function):
var myObject = new function myObj() {
this.foo = 'bar';
myObj.prototype.getFoo = function() { return this.foo; }
myObj.prototype.setFoo = function(v){ this.foo = v || this.foo; return this; }
};
but that may not work in all browsers.
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
精彩评论