Amberlamps
Amberlamps

Reputation: 40498

Passing an arbitrary object to Coffeescript's anonymous function

When I run the following Coffeescript code:

@sum = (x, y) -> x + y

I get this compiled Javascript:

(function() {

    this.sum = function(x, y) {
        return x + y;
    };

}).call(this);

Is there a way in Coffeescript to replace this in .call(this) with an arbitrary object like myObjector anything?

Upvotes: 1

Views: 596

Answers (2)

Rob W
Rob W

Reputation: 349232

(function() { and }).call(this); are not the result of compiling @sum = ..., but added by the coffee executable. This is the actual result from compiling:

this.sum = function(x, y) {
  return x + y;
};

To get a different/desired output, run coffee -b -c (or coffee -bc or coffee --bare --compile) using the following code:

(-> 
  @sum = (x, y) -> x + y
).call WHATEVER

becomes

(function() {
  return this.sum = function(x, y) {
    return x + y;
  };
}).call(WHATEVER);

Upvotes: 1

Robin Maben
Robin Maben

Reputation: 23094

myobj.sum = (x, y) -> x + y

should get compiled to (UPDATE: See Rob W's answer for compile options) :-

myobj.sum = function(x, y) {
  return x + y;
};

Isn't that what you want? So further you can call it using myobj.sum a, b

Complete code..

myobj = {}
myobj.sum = (x, y) -> x + y

alert(myobj.sum 10,4)

Upvotes: 1

Related Questions