Created
March 23, 2012 19:16
-
-
Save bhelx/2174016 to your computer and use it in GitHub Desktop.
Ruby-esque object construction in javascript
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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