CoffeeScript, lacking a var statement, automatically includes it for variables, preventing leakage into the global namespace. To purposefully access this namespace, variables must be defined as properties of the global object.
Attaching to window in the Browser
In the browser, the global object is window. Therefore, to assign a property, you can use syntax like:
window.foo = 'baz';
Managing Global Variables in Node.js
Node.js doesn't have a dedicated window object. Instead, it has exports, which is passed into the wrapped module. So, for Node.js, the assignment becomes:
exports.foo = 'baz';
Targeting Both CommonJS and the Browser
The CoffeeScript documentation suggests using the following:
root = exports ? this
This checks if exports is defined (true in Node.js) and assigns it to root if it exists. Otherwise, it assigns this to root (true in the browser).
Calling the Function
In CoffeeScript, you can write:
root.foo = -> 'Hello World'
This will declare the function foo in the global namespace, regardless of the environment.
The above is the detailed content of How do you manage global variables in CoffeeScript for both Node.js and the browser?. For more information, please follow other related articles on the PHP Chinese website!