I’m writting a library. Right now, I have everything written in a single .js file that goes like:
function doThis() {}
var thisVar = 5;
I was not sure if that was right, so I considered:
function Lib() {
this.doThis = function() {}
this.thisVar = 5;
}
var lib = new Lib();
Then, on the main program files, I would have to call everything with “lib.”, such as “lib.thisVar” or “lib.doThis();”.
Any ideas on which would be better, or are they both acceptable? Thank you in advance.
Both are acceptable theoretically. But both run the risk of naming collisions with other parts/libraries used in your application.
In the first case, you run the risk of naming collisions for the individual functions, whereas in the latter case, you run the risk of naming collisions for the function you choose for the library wrapper (
Lib).The preferred method would be to wrap them up in a separate namespace as shown in this page:
http://frugalcoder.us/post/2010/02/11/js-classes.aspx