Click here to Skip to main content
15,884,537 members
Articles / Web Development

Encapsulation in JavaScript

Rate me:
Please Sign up or sign in to vote.
4.83/5 (56 votes)
1 Oct 2010CPOL3 min read 140.2K   565   71  
This article demonstrates how to create public and private members in JavaScript through a sample.
/*
* This class helps to add / remove / swap css files dynamically.
*/

var Managers = {}; //namespace

Managers.CssManager = (function(){ //Singleton class
	
	//Private members
	var doc = document;
	var setAttributes = function(element, attributes){
		for(attribute in attributes){
			element[attribute] = attributes[attribute];
		}
	}
	
	return{
		//Public members
		addStyleSheet: function(id, url){
			var newStyleSheet = doc.createElement("link");
			setAttributes(newStyleSheet, {
				rel : "stylesheet",
				type : "text/css",
				id : id,
				href: url
			});
			doc.getElementsByTagName("head")[0].appendChild(newStyleSheet);
		},

		removeStyleSheet: function(id){
			var currentStyleSheet = doc.getElementById(id);
			if(currentStyleSheet){
				currentStyleSheet.parentNode.removeChild(currentStyleSheet);
			}
		},
		
		swapStyleSheet: function(id, url){
			this.removeStyleSheet(id);
			this.addStyleSheet(id, url);
		}
	}
})();

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer Trigent Software Private Limited
India India
I'm a software developer from south tip of India. I spent most of the time in learning new technologies. I've a keen interest in client-side technologies especially JavaScript and admire it is the most beautiful language ever seen.

I like sharing my knowledge and written some non-popular articles. I believe in quality and standards but blames myself for lagging them.

I believe in small things and they makes me happy!

Comments and Discussions