Created
August 18, 2010 23:48
-
-
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 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
// 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; | |
}} | |
}); |
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
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); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Couldn't Square.initialize be Rectangle.initialize.call(this, side, side)? That'd be baller like a ballerina.