Skip to content

Instantly share code, notes, and snippets.

@bhelx

bhelx/rb.js

Created Mar 23, 2012
Embed
What would you like to do?
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
You can’t perform that action at this time.