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?
You can't get rid of the parentheses, but you can write that function in a single line.
(-> @foo = 'bar').call obj
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.
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);
精彩评论