Chiraag Mundhe
Chiraag Mundhe

Reputation: 384

function.call in CoffeeScript

What is the shortest way of writing the following JavaScript as CoffeeScript?

var obj = {};

(function(){
  this.foo = "bar";
}).call(obj);

I can do this:

obj = {}

(->
  @foo = "bar"
).call obj

But is there a way to get rid of the parentheses around the function definition? This would almost work:

do =>
  @foo = "bar"

...except that the fat arrow operator '=>' automatically binds the function to the current value of 'this'. Is there a way to specify an alternative 'this' value when using the fat arrow?

Upvotes: 0

Views: 273

Answers (3)

Ricardo Tomasi
Ricardo Tomasi

Reputation: 35253

You had the answer from the start, but this should be added:

obj = {}

do (obj) ->
  obj.foo = "bar"

which compiles to

(function(obj){
  return obj.foo = 'bar';
})(obj);

Upvotes: 0

Trevor Burnham
Trevor Burnham

Reputation: 77416

You should accept Dogbert's answer. But if you're literally looking for the shortest way to write your code, the answer is

obj.foo = 'bar'

Resist the temptation to overuse anonymous functions.

Upvotes: 1

Dogbert
Dogbert

Reputation: 222090

You can't get rid of the parentheses, but you can write that function in a single line.

(-> @foo = 'bar').call obj

Upvotes: 2

Related Questions