Home >Web Front-end >JS Tutorial >How do you Define Global Variables in CoffeeScript?

How do you Define Global Variables in CoffeeScript?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-11-30 05:39:10556browse

How do you Define Global Variables in CoffeeScript?

Defining 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.

Browser Environment: 'Attaching to Window'

In the browser, the global object is the window object. To create a global variable named foo, you would write:

window.foo = 'baz'

Node.js Environment: 'Attaching to Exports'

In Node.js, the global object is not available as window. Instead, you should assign global variables to the exports object:

exports.foo = 'baz'

Targeting Both CommonJS and Browsers

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.

Example: Declaring a Global Function in CoffeeScript

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn