Skip to content

Instantly share code, notes, and snippets.

@bhelx
Created March 23, 2012 19:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save bhelx/2174016 to your computer and use it in GitHub Desktop.
Save bhelx/2174016 to your computer and use it in GitHub Desktop.
Ruby-esque object construction in javascript
// kind of like ruby openstruct
var OpenObject = function () {
this.construct = function (defaults, params) {
for (var attr in defaults) this[attr] = defaults[attr];
for (var attr in params) this[attr] = params[attr];
};
}
var Circle = function (opts) {
this.construct({
color: '#ffff00',
radius: 20
}, opts);
};
Circle.prototype = new OpenObject();
Circle.prototype.constructor = Circle;
Circle.prototype.toString = function () {
return 'radius: '+this.radius+' color: '+this.color;
}
var a = new Circle({ color: '#ff00ff' });
console.log(a.toString()); //=> 'radius: 20 color: #ff00ff'
//maybe a slightly more GC sane way?
var Square = function (opts) {
var DEFAULTS = {
color: '#ffff00',
side: 20
};
this.construct(DEFAULTS, opts);
};
Square.prototype = new OpenObject();
Square.prototype.constructor = Circle;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment