Reputation: 850
I am looking into systems for making JavaScript libraries. I have seen most of the libraries using methods such as "Immediately Invoked Function Expression". This method to me makes the code quite unreadable.
I want to know what are the advantages of using this method?
And what are limitations of using the basic .prototype
system for creating a library?
For instance, what is wrong with using this pattern to create a library?:
function Library(){
this.property = 'val';
}
Library.prototype.method = function(){
// a method
}
//and to use the library
var lib = new Library();
Upvotes: 2
Views: 1082
Reputation: 34556
Immediately-executed functions are essentially just a means of avoiding polluting the global scope with variables that should be private.
Your approach is fine, but what if you want your library to internally reference private data that should not be part of your public API? Example:
var Some_class = (function() {
var foobar = 'foo'; //private; library can read it but public API can't
var api = function() { /* constructor */ };
api.prototype.method = function() { return foobar == 'foo' ? 1 : 0; }
return api;
})();
var instance = new Some_class();
instance.method();
foobar
is a private (i.e. internal) variable for use BY your library, but not publicly accessible via its API.
Upvotes: 2