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
Release: 2024-11-29 19:03:13
Original
307 people have browsed it

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';
Copy after login

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';
Copy after login

Targeting Both CommonJS and the Browser

The CoffeeScript documentation suggests using the following:

root = exports ? this
Copy after login

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'
Copy after login

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!

source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template