Home >Web Front-end >JS Tutorial >How do you manage global variables in CoffeeScript for both Node.js and the browser?

How do you manage global variables in CoffeeScript for both Node.js and the browser?

DDD
DDDOriginal
2024-11-29 19:03:13324browse

How do you manage global variables in CoffeeScript for both Node.js and the browser?

Global Variables in CoffeeScript: Attaching to Window or Exports

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!

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