Reputation: 3640
The following CoffeeScript code:
do (a) ->
console.log a
generates this:
(function(a) {
return console.log(a);
})(a);
How do I pass a value to a like this?
(function(a) {
return console.log(a);
})("hello");
Upvotes: 13
Views: 7930
Reputation: 1259
If you're using the Module Pattern, this is useful to use the $ global when using multiple Javascript libraries that may conflict with each other:
mySingleton = do ($ = jQuery) ->
colorIt -> $('.colorme').css('backgroundColor', 'red')
mySingleton.colorIt()
Upvotes: 3
Reputation: 9914
you could do this
do (a = "foo")->
console.log a
But really why would you do this? WHat is the more complete use case you are trying to implement
Upvotes: 2
Reputation: 19219
do (a = 'hello') ->
console.log a
Will generate exactly what you want.
Though, i have to admit that i can't see the point of doing that. If you really want a
to take the literal value 'hello'
inside that scope, then why make another scope? With a
being a normal variable declared as a = 'hello'
will be enough. Now, if you want to replace a
with the value of another variable (that might change in a loop or something) and do do (a = b) ->
then i think it makes more sense, but you could simple do do (a) ->
and just use a
instead of b
inside the do
scope.
Upvotes: 21
Reputation: 22258
do
is a special keyword in CoffeeScript. It creates a closure. I think you want something like this:
log = (msg) ->
console.log msg
Compiles to:
var log;
log = function(msg) {
return console.log(msg);
};
Use it like any other function: log("hello")
Upvotes: 2