I’ve seen several styles in JavaScript. Curious to the difference between them in terms of readability, optimization, and variable scoping. Pro and Cons would be appreciated.
Method A:
function MyObj(options) {
this.options = options;
}
MyObj.prototype.getOptions = function() {
return this.options;
};
Method B:
var MyObj = (function() {
function MyObj(options) {
this.options = options;
}
MyObj.prototype.getOptions = function() {
return this.options;
};
return MyObj;
})();
Someone once said the wrapper was for dealing with named functions in IE. I noticed that by placing a wrapper allows for compartmentalizing variables and functions that would be static to the object.
However I’ve also had many complain that the wrapping was inefficient or odd. CoffeeScript also compiles to method B. So when writing JS by hand which is best practise and when should one method be used over another?
The second is using a module pattern. In this simplified example, there’s no real difference, but the second one should generally be preferred for variable encapsulation, additionally it avoids polluting the global namespace unnecessarily.