Counter examples

These examples illustrate four ways of creating JavaScript objects: (1) object literals, (2) cloning (delegating to) a prototype, (3) calling a constructor, and (4) returning a closure. Example (5) illustrates a form of "inheritance".


Object literals

0

var counter1 = {
	val : 0,
	name : 'counter1',
	inc : function() { this.val++; update(this); },
	dec : function() { this.val--; update(this); }
}	

Cloning a prototype

0

var counter2 = Object.create(counter1);
counter2.val = 0;
counter2.name = 'counter2';

Calling a constructor

0

function Counter(name) {
	this.val = 0;
	this.name = name;
}
Counter.prototype.inc = counter1.inc;
Counter.prototype.dec = counter1.dec;
var counter3 = new Counter('counter3');

Returning a closure

0

var counter4 = (function(name) {
	var val = 0;
	var name = name;
	return {
		inc : function() { val++; update(this); },
		dec : function() { val--; update(this); },
		get val() { return val; },
		get name() { return name; }
	}
})('counter4');

A Colored Counter

0

function ColoredCounter(name, color) {
	this.val = 0;
	this.name = name;
	this.color = color;
	var that = this;
	window.onload = function() {
		document.getElementById(that.name).style.color = that.color;
	};
}
ColoredCounter.prototype = new Counter('x');
var blueCounter = new ColoredCounter('blueCounter', 'Blue');