mardi 15 décembre 2015

JavaScript Avoiding the global namespace pollution by objects created using constructor pattern

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

  1. pollution of the global namespace since the Book() object is now visible in the global scope.
  2. Security issue as any one can create objects without namespace from console.

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)?

Aucun commentaire:

Enregistrer un commentaire