How do I define global variables in CoffeeScript?

后端 未结 8 2221
说谎
说谎 2020-11-22 05:41

On Coffeescript.org:

bawbag = (x, y) ->
    z = (x * y)

bawbag(5, 10) 

would compile to:

var bawbag;
bawbag = function(         


        
8条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-11-22 05:46

    If you're a bad person (I'm a bad person.), you can get as simple as this: (->@)()

    As in,

    (->@)().im_a_terrible_programmer = yes
    console.log im_a_terrible_programmer
    

    This works, because when invoking a Reference to a Function ‘bare’ (that is, func(), instead of new func() or obj.func()), something commonly referred to as the ‘function-call invocation pattern’, always binds this to the global object for that execution context.

    The CoffeeScript above simply compiles to (function(){ return this })(); so we're exercising that behavior to reliably access the global object.

提交回复
热议问题