Home > Web Front-end > JS Tutorial > How Can I Define Global Variables in CoffeeScript?

How Can I Define Global Variables in CoffeeScript?

Barbara Streisand
Release: 2024-11-15 05:00:02
Original
548 people have browsed it

How Can I Define Global Variables in CoffeeScript?

Defining Global Variables in CoffeeScript

CoffeeScript prevents variables from leaking into the global namespace by automatically inserting the var statement for all variables in the compiled JavaScript code. Therefore, to define global variables in CoffeeScript, you need to attach them as properties on the global object.

In the Browser

In the browser, the global object is the window object. Thus, to define a global variable, you would write:

window.foo = 'baz'
Copy after login

In Node.js

In Node.js, there is no window object. Instead, there is an exports object that gets passed into the wrapper that wraps the Node.js module. To define a global variable in Node.js, you would write:

exports.foo = 'baz'
Copy after login

Targeting Both CommonJS and the Browser

If you want to target both CommonJS and the browser with your CoffeeScript code, you can use the following syntax to define global variables:

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

This syntax will check if the exports object exists (which is the case in Node.js) and if so, it will assign the global variable to the exports object. Otherwise, it will assign the global variable to the this object (which is the window object in the browser).

The above is the detailed content of How Can I Define Global Variables in CoffeeScript?. For more information, please follow other related articles on the PHP Chinese website!

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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template