Skip to content

Instantly share code, notes, and snippets.

@mbroadst
Created February 25, 2016 17:31
Show Gist options
  • Save mbroadst/619e10a2ef86b656602b to your computer and use it in GitHub Desktop.
Save mbroadst/619e10a2ef86b656602b to your computer and use it in GitHub Desktop.
// with defined properties
function accessors(index) {
return {
enumerable: true, configurable: false,
get: function() { return this._value[index]; },
set: function(value) { this._value[index] = value; }
};
}
function defineTypeWithDefinedProperties(fields) {
function Type(values) { this._value = values || []; }
var _len = fields.length, properties = {};
for (var i = 0; i < _len; ++i) properties[fields[i].name] = accessors(i);
Type.prototype = Object.create(Object.prototype, properties);
return Type;
}
// with get/set on prototype
function defineTypeWithGetSetOnPrototype(fields) {
function Type(values) { this._value = values || []; }
var _len = fields.length, properties = {};
for (var i = 0; i < _len; ++i) properties[fields[i].name] = i;
Type.prototype.properties = properties;
Type.prototype.get = function(prop) {
return this._value[Type.prototype.properties[prop]];
};
Type.prototype.set = function(prop, value) {
this._value[Type.prototype.properties[prop]] = value;
};
return Type;
}
// prep
var fields = [ { name: 'first' }, { name: 'second' } ];
var WithDefinedProperties = defineTypeWithDefinedProperties(fields);
var WithGetSetOnPrototype = defineTypeWithGetSetOnPrototype(fields);
var definedWithValues = new WithDefinedProperties([1, "two"]);
var definedWithNoValues = new WithDefinedProperties();
var getSetWithValues = new WithGetSetOnPrototype([1, "two"]);
var getSetWithNoValues = new WithGetSetOnPrototype();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment