开发者

function.call in CoffeeScript

开发者 https://www.devze.com 2023-03-29 16:58 出处:网络
What is the shortest way开发者_开发百科 of writing the following JavaScript as CoffeeScript? var obj = {};

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

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号