Content with Style

Web Technique

JS and objects

by Pascal Opitz on August 28 2008, 10:22

Just a quick moment trying to explain the different approaches to using objects in Javascript to a fellow co-worker:


// Normal object with new keyword
var myClass = function() {
	var privateMethod = function() {
	}

	this.publicFunc = function() {
	}
}

var myObj1 = new myClass();
var myObj2 = new myClass();
var myObj3 = new myClass();


// Singleton with new keyword
var mySingleton = new function() {
	this.foo = function() {}
}
mySingleton.foo();


// Singleton without assignment - YUI style
(function(){
})();

// Object literal
var myObjLiteral = {
	'foo' : function() {},
	'bar' : function() {}
}

I am sure that I missed out some important ones, but feel free just to put them into the comments.