Skip to content

Instantly share code, notes, and snippets.

@jonnyreeves
Created June 11, 2012 08:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jonnyreeves/2909133 to your computer and use it in GitHub Desktop.
Save jonnyreeves/2909133 to your computer and use it in GitHub Desktop.
JavaScript Object Factory Functions
// Wrap everything in an IIFE to avoid any globals leaking out.
(function (global) {
// Object Prototype, all instances created via 'matrix22' factory method will
// inherit from this object.
var matrix22Proto = {
zero: function() {
for (var i = 0; i < this.m.length; ++i) {
this.m[i] = 0.0;
}
return this;
}
};
// Factory function for creating new instances of the matrix22 object, note how
// it's not a constructor function so doesn't need to be called with `new`.
global.MW.matrix22 = function () {
// Emulate ES5's Object.create()
var Result = function () { };
Result.prototype = matrix22Proto;
// Initialise the new object.
Result.rows = 2;
Result.cols = 2;
Result.m = [];
// Return the new instance.
return new Result();
};
})(this);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment