https://github.com/creationix/proto
Adds nice utilities to Object.prototype for JavaScript using Object.defineProperty
https://github.com/creationix/proto
Last synced: about 1 year ago
JSON representation
Adds nice utilities to Object.prototype for JavaScript using Object.defineProperty
- Host: GitHub
- URL: https://github.com/creationix/proto
- Owner: creationix
- Created: 2010-03-18T01:45:50.000Z (over 16 years ago)
- Default Branch: master
- Last Pushed: 2010-08-13T23:59:59.000Z (almost 16 years ago)
- Last Synced: 2025-03-24T04:14:01.332Z (about 1 year ago)
- Language: JavaScript
- Homepage:
- Size: 93.8 KB
- Stars: 32
- Watchers: 2
- Forks: 2
- Open Issues: 0
-
Metadata Files:
- Readme: README.markdown
Awesome Lists containing this project
README
# Proto
This simple js library adds four functions to Object.prototype. Since this only modifies global objects and doesn't export any structures, you don't need the return value when calling `require('proto')`.
## Object.prototype
All functions added to `Object.prototype` are usable from any object in JavaScript.
### Object.prototype.forEach(callback[, thisObject])
This is the most useful of the additions. It allows you to forEach over an `Object` instance's local properties and values just like you can already do with `Array` instances.
require('proto');
({name: "Tim", age: 28}).forEach(function (value, key) {
console.log(key + " = " + JSON.stringify(value));
});
### Object.prototype.map(callback[, thisObject])
This works like forEach, except returns an `Array` instance with the returned values of the function calls.
require('proto');
var pairs = ({name: "Tim", age: 28}).map(function (value, key) {
return key + " = " + value;
});
// pairs is ["name = Tim", "age = 28"]
### Object.prototype.new(args...)
Creates a new version of the current object and calls it's `initialize` function if one exists with the same arguments passed to new.
require('proto');
var Rectangle = {
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);
### Object.prototype.extend(newObject)
Sets the current object as the prototype to the passed in object and returns the new passed in object.
// 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);