Home >Web Front-end >JS Tutorial >How do you Define Global Variables in CoffeeScript?
In CoffeeScript, the absence of a dedicated var statement means that all variables are implicitly declared as local. This prevents inadvertent leaks into the global namespace during compilation to JavaScript.
To define global variables, you need to assign them as properties to the global object.
In the browser, the global object is the window object. To create a global variable named foo, you would write:
window.foo = 'baz'
In Node.js, the global object is not available as window. Instead, you should assign global variables to the exports object:
exports.foo = 'baz'
The CoffeeScript documentation suggests using the root variable to determine the appropriate global object based on whether exports is defined (which is the case in Node.js) or not (which implies a browser environment):
root = exports ? this root.foo = 'baz'
This ternary expression assigns root to exports if exports is defined, and to this (the global context in Node.js, or window in the browser) otherwise.
root = exports ? this root.foo = -> 'Hello World'
This code declares a global function named foo in either the Node.js (via exports) or browser (via window) global object.
The above is the detailed content of How do you Define Global Variables in CoffeeScript?. For more information, please follow other related articles on the PHP Chinese website!