user1096557
user1096557

Reputation:

How to return a global variable value from inside a function in coffeescript?

I have the following:

 $(document).ready ->
    root = exports ? this
    root.hello = -> 'hello world'
    world = ->
        root.hello
    alert world

The alert message pops up:

function() {
       root.hello }

I want it to popup "hello world". How do I return coffeescript global variables from within a function?

Upvotes: 0

Views: 60

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1075567

Two things you have to do:

First, remove the -> in

root.hello = -> 'hello world'
//           ^^ remove this

That -> means you're assigning a function to root.hello.

Then, you need to add () after world when doing the call, so you're calling world, not just referring to it.

alert world()
//         ^^ Add these

So:

$(document).ready ->
    root = exports ? this
    root.hello = 'hello world'
    world = ->
        root.hello
    alert world()

Upvotes: 2

Related Questions