Home >Web Front-end >JS Tutorial >How do I define Global Variables in CoffeeScript?

How do I define Global Variables in CoffeeScript?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-11-28 14:02:11426browse

How do I define Global Variables in CoffeeScript?

How do I define Global Variables in CoffeeScript?

Your CoffeeScript code compiles to JavaScript without var statements, automatically inserting them for all variables to prevent leaking to the global namespace. To define global variables intentionally, you must assign them as properties of the global object.

'Attach them as properties on window' in the Browser

The browser's global object is the window. To define a global variable, use:

window.foo = 'baz';

Node.js

Node.js lacks a window object. Instead, it has an exports object passed into the wrapper that encloses the module. For Node.js, use:

exports.foo = 'baz';

Targeting Both CommonJS and the Browser

The CoffeeScript documentation suggests the following code to target both CommonJS and the browser:

root = exports ? this

This checks if exports is defined (Node.js) and assigns it to root if true, otherwise assigning the browser's global object (window).

In Node.js, you can assign directly to the exports object, which is returned by the require function. However, in CoffeeScript, use the following to define a global function:

root = exports ? this
root.foo = ->
  'Hello World'

This assignes the function foo to the global namespace, regardless of whether you're in the browser or using Node.js.

The above is the detailed content of How do I 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