CoffeeScript prevents variables from leaking into the global namespace by automatically inserting the var statement for all variables in the compiled JavaScript code. Therefore, to define global variables in CoffeeScript, you need to attach them as properties on the global object.
In the browser, the global object is the window object. Thus, to define a global variable, you would write:
window.foo = 'baz'
In Node.js, there is no window object. Instead, there is an exports object that gets passed into the wrapper that wraps the Node.js module. To define a global variable in Node.js, you would write:
exports.foo = 'baz'
If you want to target both CommonJS and the browser with your CoffeeScript code, you can use the following syntax to define global variables:
root = exports ? this root.foo = -> 'Hello World'
This syntax will check if the exports object exists (which is the case in Node.js) and if so, it will assign the global variable to the exports object. Otherwise, it will assign the global variable to the this object (which is the window object in the browser).
The above is the detailed content of How Can I Define Global Variables in CoffeeScript?. For more information, please follow other related articles on the PHP Chinese website!