I want to add the ability to extend javascript objects by adding a method to the prototype.
The method will receive one or more other objects and will add all of the key/values to this
.
This is what I came up with:
Object::extend = (objects...) ->
@[key] = value for key, value of object for object in objects
or this:
Object::extend = (objects...) ->
for object in objects
for key, value of object
@[key] = value
Both work as expected, and compile into the same javascript code:
var __slice = [].slice;
Object.prototype.extend = function() {
var key, object, objects, value, _i, _len, _results;
objects = 1 <= arguments.length ? __slice.call(arguments, 0) : [];
_results = [];
for (_i = 0, _len = objects.length; _i < _len; _i++) {
object = objects[_i];
_results.push((function() {
var _results1;
_results1 = [];
for (key in object) {
value = object[key];
_results1.push(this[key] = value);
}
return _results1;
}).call(this));
}
return _results;
};
What I'm not too happy about is the whole results thing that is created per for loop which is completely redundant for my purpose.
Is there a way to get a code more like:
Object.prototype.extend = function() {
var key, object, objects, value, _i, _len;
objects = 1 <= arguments.length ? __slice.call(arguments, 0) : [];
for (_i = 0, _len = objects.length; _i < _len; _i++) {
object = objects[_i];
(function() {
for (key in object) {
value = object[key];
this[key] = value;
}
}).call(this);
}
};
Thanks.
Edit
I'm aware that I can simply embed javascript code, but looking for a coffeescript solution.