1

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?

4
  • Your code is incomplete. Please add what's before/after @sum = (x, y) -> x + y1 Commented Aug 24, 2012 at 9:23
  • No, this is actually my complete code. This is why I am asking how to change the this object, so that sum() is added to whatever object I want. Commented Aug 24, 2012 at 9:25
  • (function() { and }).call(this); are not compiled from @sum = .... These are the result of running coffee without the --bare flag. this is the actual result from compiling. Commented Aug 24, 2012 at 9:30
  • @RobW: I did not know that. I run coffee -c example.coffee in my console and I always get that anonymous function wrapper. I thought that was standard. Commented Aug 24, 2012 at 9:32

2 Answers 2

1

(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);
Sign up to request clarification or add additional context in comments.

1 Comment

That is pretty much what I was looking for. Thanks! The flag does the trick.
1
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)

2 Comments

No, I want to know whether that anonymous function can in any way be modified like for instance passing a different object than this
@Amberlamps: Why, is it because you want to extend the sum function into whatever object you pass? And then again, that anonymous function cannot ever be called again, so I don't see the point.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.