Skip to content

Instantly share code, notes, and snippets.

@nicholascloud
Last active October 2, 2015 17:57
Show Gist options
  • Save nicholascloud/2288974 to your computer and use it in GitHub Desktop.
Save nicholascloud/2288974 to your computer and use it in GitHub Desktop.
blog-historical-object
//context: http://www.nicholascloud.com/2012/04/historical-javascript-objects/
var historicalObject = (function () {
var _pushProto = function (obj) {
function EmptyObject () {}
EmptyObject.prototype = obj || Object.prototype;
var other = new EmptyObject();
if (other.__version !== undefined) {
other.__version++;
} else {
other.__version = 1;
}
return other;
};
var _popProto = function (obj) {
var proto = Object.getPrototypeOf(obj);
if (proto === Object.prototype) {
return obj;
}
return proto;
};
return {
create: function (base) {
var obj = _pushProto(base);
obj.revise = function () {
return _pushProto(this);
};
obj.revert = function (howFar) {
if (typeof howFar !== 'number') {
howFar = 1;
}
var other = _popProto(this);
howFar--;
if (howFar === 0) {
return other;
}
return other.revert(howFar);
};
return obj;
}
};
})();
var person = function (name, permissions) {
return historicalObject.create({
setName: function (name) {
var other = this.revise();
other.getName = function () {
return name;
};
return other;
},
getName: function () {
return name;
},
elevate: function () {
if (!permissions.indexOf('admin') < 0) {
return;
}
var _this = this;
var other = this.revise();
other.isAdmin = true;
other.toString = function () {
return "(admin) " + _this.toString();
};
return other;
},
toString: function toString () {
var str = "[" + this.__version + "]::" + this.getName();
var proto = Object.getPrototypeOf(this);
if (proto.hasOwnProperty('__version')) {
str += ' -> ' + proto.toString();
}
return str;
}
});
};
var p = person('Walter', ['admin'])
.setName('Walter Williams')
.setName('Walter T. Williams')
.setName('Walt');
console.log(p.toString());
p = p.revert();
console.log(p.toString());
p = p.elevate();
console.log(p.toString());
p = p.revert();
console.log(p.toString());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment