I am relatively new to JavaScript, which means i only used jquery, meteor.js and some WebGL (but in no larger project) Since i am very interested in Computer graphics, i want to write a simple WebGL library ( like three.js oder pixie.js but of course more simpler)
The Problem i am facing is for example when i have a namespace MyLibrary.renderer=... i only want to expose MyLibrary. What i am looking for is that a client can only write var renderer =new MyLibrary.renderer()
However inside the file renderer i will need a couple of other classes. The Problem so far is that i import them via <script> but as i mentioned i dont want to expose this classes, but instead only the final namespace MyLibrary. So i was looking for a way to import classes .
I currently looked up browserify but i think i didnt properly understand. Can someone provide also an example of how to use browserify with namespace and classes? And if possible explain how a library like three.js manage/structure their Code?
Write a self executing closure function. This protects your code from mixing up with other library's scope and is generally good practice. Of course it will not prevent others from reading your code.
(function ()
{
var _MyLibrary = Object.create(null);
// do stuff
window.MyLibrary = _MyLibrary;
})();
You can write and expose a constructor function instead of an object as well, however, that's old school. You should prefer generating properties on an object by Object.defineProperties() method.
Instead of loading other codes into <script> tags consider fetching them via AJAX from within your library.