Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

Functions in Coffeescript can't be hoisted, since it doesn't function declarations, only function expressions. How can I write a macro to add function declarations to coffeescript?

Specifically, I want:

foo(bar, baz) ->

to compile to:

function foo(bar, baz) {
}

instead of:

foo(bar, baz)(function() {});
share|improve this question

2 Answers 2

up vote 0 down vote accepted

I don't think you can do that unless you want to write foo in JavaScript and embed it in your CoffeeScript using backticks. For example:

console.log f 'x'
`function f(x) { return x }`

becomes this JavaScript:

console.log(f('x'));
function f(x) { return x };

and f will be executed as desired.

If you want to change how CoffeeScript interprets foo(bar, baz) -> then you'll have to edit the parser and deal with all the side effects and broken code. The result will be something similar to CoffeeScript but it won't be CoffeeScript.

CoffeeScript and JavaScript are different languages, trying to write CoffeeScript while you're thinking in JavaScript terms will just make a mess of things; they share a lot and CoffeeScript is compiled/translated to JavaScript but they're not the same language so you work with them differently. Don't write C code in C++, don't write Java in Scala, don't write JavaScript in CoffeeScript, ...

share|improve this answer

I am really not sure what you try to accomplish but the closest thing to what you want is this

func = (name) ->
    (body) ->
        window[name] = body

func("foo") (arg)-> console.log(arg)

foo("lala") #prints lala

I would also suggest to stay with the CoffeeScript syntax a "macro" that redresses such an important thing like a function declaration is bound to create confusion. Especially as you dont win anything - quite the contrary.

share|improve this answer
    
But this won't hoist the function definition to the top of the scope the way function f() { ... } does so foo('x'); func('foo') (x) -> console.log(x) will give you a TypeError whereas the JavaScript foo('x'); function foo(x) { console.log(x) } will work. –  mu is too short Jul 5 '13 at 5:35
    
you are right, it doesnt hoist the function. –  robkuz Jul 5 '13 at 10:22

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.