Skip to content

Instantly share code, notes, and snippets.

@DylanFM
Created December 3, 2009 00:44
Show Gist options
  • Save DylanFM/247783 to your computer and use it in GitHub Desktop.
Save DylanFM/247783 to your computer and use it in GitHub Desktop.
// NS is a global variable for a namespace for the app's code
var NS = {};
NS.Obj = (function() {
// Private vars and methods always available to returned object via closure
return {
method: function() {
}
};
}());
// crockford.com/codecamp <-- slides
// Pseudoclassical
function Gizmo (id) {
this.id = id;
}
Gizmo.prototype.toString = function() {
return "gizmo " + this.id;
};
var g = new Gizmo(1);
g.toString(); // "gizmo 1"
// This is all bad stuff (confusing/complicated):
function Hoozit (id) {
this.id = id;
}
Hoozit.prototype = new Gizmo();
Hoozit.prototype.test - function(id) {
return this.id === id;
};
var h = new Hoozit(1);
Hoozit.test(g.id);
// Prototypal
// Better than above. Prototypal and doesn't need the stuff done in pseudoclassical
var oldObj = {
first: function() {},
second: function() {}
};
var newObj = Object.create(oldObj);
newObj.third = function() {};
var myDoppelganger = Object.create(newObj);
myDoppelganger.first();
// Functional inheritance / Power constructors
// Simple pattern for making objects with private information
function myPowerConstructor (x) {
var that = otherMaker(x);
var secret = f(x);
that.priv = function() {
// ... secret x that ...
};
return that;
}
// A version of the above pattern in this form
function gizmo (id) {
return {
toString: function() {
return "gizmo " + id;
}
};
}
function hoozit (id) {
var that = gizmo(id);
that.test = function(testid) {
return testid === id;
};
return that;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment