Extending Javascript Objects with CoffeeScript

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 add all the keys / values ​​to this.
Here is what I came up with:

Object::extend = (objects...) ->
    @[key] = value for key, value of object for object in objects

or that:

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 with is all the results that are generated in a cycle that is completely redundant for my purpose.
Is there a way to get the code more:

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);
  }
};

Thank.


Edit

I know that I can just embed javascript code, but am looking for a solution for coffeescript.

+5
source share
1 answer

return:

Object::extend = (objects...) ->
    for object in objects
        for key, value of object
            @[key] = value
    return 

:

var __slice = [].slice;

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];
    for (key in object) {
      value = object[key];
      this[key] = value;
    }
  }
};

CoffeeScript , CoffeeScript . , CoffeeScript _results , return, . return, " ", CS → JS , , _results.

+4

All Articles