1. By Direct Assignment
var myApp = {}
myApp.id = 0;
myApp.next = function() {
return myApp.id++;
}
myApp.reset = function() {
myApp.id = 0;
}
window.console && console.log(
myApp.next(),
myApp.next(),
myApp.reset(),
myApp.next()
); //0, 1, undefined, 0
var myApp = {}
myApp.id = 0;
myApp.next = function() {
return this.id++;
}
myApp.reset = function() {
this.id = 0;
}
myApp.next(); //0
myApp.next(); //1
var getNextId = myApp.next;
getNextId(); //NaN whoops!
2. Using Object Literal Notation
var myApp = {
id: 0,
next: function() {
return this.id++;
},
reset: function() {
this.id = 0;
}
}
window.console && console.log(
myApp.next(),
myApp.next(),
myApp.reset(),
myApp.next()
) //0, 1, undefined, 0
3. Module Pattern
var myApp = {
id: 0,
next: function() {
return this.id++;
},
reset: function() {
this.id = 0;
}
}
window.console && console.log(
myApp.next(),
myApp.next(),
myApp.reset(),
myApp.next()
) //0, 1, undefined, 0
4. Supply a Namespace Argument
var myApp = {};
(function(context) {
var id = 0;
context.next = function() {
return id++;
};
context.reset = function() {
id = 0;
}
})(myApp);
window.console && console.log(
myApp.next(),
myApp.next(),
myApp.reset(),
myApp.next()
) //0, 1, undefined, 0
var myApp = {};
(function(context) {
var id = 0;
context.next = function() {
return id++;
};
context.reset = function() {
id = 0;
}
})(this);
window.console && console.log(
next(),
next(),
reset(),
next()
) //0, 1, undefined, 0
var subsys1 = {}, subsys2 = {};
var nextIdMod = function(startId) {
var id = startId || 0;
this.next = function() {
return id++;
};
this.reset = function() {
id = 0;
}
};
nextIdMod.call(subsys1);
nextIdMod.call(subsys2,1000);
window.console && console.log(
subsys1.next(),
subsys1.next(),
subsys2.next(),
subsys1.reset(),
subsys2.next(),
subsys1.next()
) //0, 1, 1000, undefined, 1001, 0
nextIdMod();
window.console && console.log(
next(),
next(),
reset(),
next()
) //0, 1, undefined, 0
//library code
var protoQueryMooJo = function() {
//everything
}
//user code
var thirdParty = {};
protoQueryMooJo.apply(thirdParty);