Skip to content

Instantly share code, notes, and snippets.

@creationix
Created August 18, 2010 23:48
Show Gist options
  • Save creationix/536572 to your computer and use it in GitHub Desktop.
Save creationix/536572 to your computer and use it in GitHub Desktop.
Port of my proto library, but doesn't mess with Object.prototype
// This is my proto library but without changing Object.prototype
// Then only sub-objects of Class have the special properties.
var Class = module.exports = Object.create(Object.prototype, {
// Implements a forEach much like the one for Array.prototype.forEach, but for
// any object.
forEach: {value: function forEach(callback, thisObject) {
var keys = Object.keys(this);
var length = keys.length;
for (var i = 0; i < length; i++) {
var key = keys[i];
callback.call(thisObject, this[key], key, this);
}
}},
// Implements a map much like the one for Array.prototype.map, but for any
// object. Returns an array, not a generic object.
map: {value: function map(callback, thisObject) {
var accum = [];
var keys = Object.keys(this);
var length = keys.length;
for (var i = 0; i < length; i++) {
var key = keys[i];
accum[i] = callback.call(thisObject, this[key], key, this);
}
return accum;
}},
// Implement extend for easy prototypal inheritance
extend: {value: function extend(obj) {
obj.__proto__ = this;
return obj;
}},
// Implement new for easy self-initializing objects
new: {value: function () {
var obj = Object.create(this);
if (obj.initialize) obj.initialize.apply(obj, arguments);
return obj;
}}
});
var Class = require('class');
var Rectangle = Class.extend({
initialize: function initialize(width, height) {
this.width = width;
this.height = height;
},
get area() {
return this.width * this.height;
}
});
var rect = Rectangle.new(2, 4);
console.log(rect.area);
// Assuming the code from above
var Square = Rectangle.extend({
initialize: function initialize(side) {
this.width = side;
this.height = side;
}
});
var square = Square.new(15);
console.log(square.area);
@isaacs
Copy link

isaacs commented Aug 19, 2010

Couldn't Square.initialize be Rectangle.initialize.call(this, side, side)? That'd be baller like a ballerina.

@creationix
Copy link
Author

sure, that works too

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment