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".
var counter1 = { val : 0, name : 'counter1', inc : function() { this.val++; update(this); }, dec : function() { this.val--; update(this); } }
var counter2 = Object.create(counter1); counter2.val = 0; counter2.name = 'counter2';
function Counter(name) { this.val = 0; this.name = name; } Counter.prototype.inc = counter1.inc; Counter.prototype.dec = counter1.dec; var counter3 = new Counter('counter3');
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');
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');