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() {});
有帮助吗?

解决方案

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, ...

其他提示

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.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top