Reputation: 1239
For creating a JS library, I am internally creating objects using constructor pattern. Now each type of object is in it's own file, so say book is in book.js. All the files are concatenated and then minified.
book.js
--------
function Book (data) {
this.data = data;
}
Book.prototype.rent = function(name) {
console.log("Rent the book to " + name);
}
Now once the page with the library is loaded, I can notice that from the browser console one can create book objects directly.
var b = new Book("somedata");
I see 2 issues here
The library is actually under a namespace using a revealing module pattern. Is there anyway the issues I have mentioned above can be safely handled? Anyway to hide the objects from global namespace (console)?
Upvotes: 1
Views: 2622
Reputation: 665020
Security issue as any one can create objects without namespace from console.
That's not an issue, anyone can create objects on your namespace from the console as well.
pollution of the global namespace since the
Book()
object is now visible in the global scope. The library is actually under a namespace using a revealing module pattern.
If you are loading all those files as scripts then they will put the classes declared therein in the global namespace. It's unavoidable to use the global namespace somehow, but you can put all of your objects on that custom library namespace right away, using the revealing module pattern. You would need to wrap each of those files in an IEFE that attaches the respective class to City.Library
:
City.Library.Book = (function() {
function Book (data) {
this.data = data;
}
Book.prototype.rent = function(name) {
console.log("Rent the book to " + name);
};
return Book;
}());
Alternatively, treat the files as modules (ES6 is preferred) and let a module loader/bundler do this work for you automatedly.
Upvotes: 1
Reputation: 171
What you can do is that you can use require module on server side and create grunt task to run browserify task on entry point file so that all your code will be converted into one file and won't be accessible from global namespace. checkout http://browserify.org for more information.
Upvotes: 2
Reputation: 2452
You can wrap them in closures to keep them away from global, but, there is a fundamental problem with this—you want your functions/constructors/whatevers to be accessible!
Approaches like browserify wrap code in files in closures but keeps track of them so that when you need them you can access them. It uses commonJS modules as a means of accessing and organising modular code. I would suggest reading documentation for browserify as using it would solve both problems, although it would enforce a module system on your end users (I'd say this is generally a good thing, at least it is a worthwhile thing, but, that is for you to decide based on your specific case)
I should also point out that there are other solutions for writing modular code as well, such as webpack or jspm
Upvotes: 0