Webessence

Javascript encapsulation

The jQuery library is a good source for learning. An example of namespacing a library with a "no conflict" functionality a la jQuery.

myLib = "I'm a string!";

(function(global, undefined) {
// Save old value (if there is one).
var _myLib = global.myLib;

// This is the place to add to the global context.
var myLib = global.myLib = {};

var privateVar = "This is a private var";

function privateFunction() {
return "This is a private function";
}

myLib.Customer = function(name, age) {
this.name = name;
this.age = age;
};

myLib.Customer.prototype.toString = function() {
return this.name + ", " + this.age + " years";
};

// Access the global scope.
myLib.setTitle = function(title) {
global.document.title = title;
};

myLib.noConflict = function() {
global.myLib = _myLib;
return myLib;
}
})(window);

To use it:

myLib.setTitle("Hello 1");
var newMyLib = myLib.noConflict();
alert("Ok");
newMyLib.setTitle("Hello 2");
alert(myLib); // I'm a string!

Some links:

Javascript | 2011-11-12 16:54:11 | Comments (0)

Comments

No comments.
Comments are turned off after 90 days.