On Coffeescript.org:
bawbag = (x, y) ->
z = (x * y)
bawbag(5, 10)
would compile to:
var bawbag;
bawbag = function(x, y) {
var z;
return (z = (x * y));
};
bawbag(5, 10);
compiling via coffee-script under node.js wraps that so:
(function() {
var bawbag;
bawbag = function(x, y) {
var z;
return (z = (x * y));
};
bawbag(5, 10);
}).call(this);
Docs say:
If you’d like to create top-level variables for other scripts to use,
attach them as properties on window, or on the exports object in
CommonJS. The existential operator (covered below), gives you a
reliable way to figure out where to add them, if you’re targeting both
CommonJS and the browser: root = exports ? this
How do I define Global Variables then in CoffeeScript. What does ‘attach them as properties on window’ mean?
Since coffee script has no
varstatement it automatically inserts it for all variables in the coffee-script, that way it prevents the compiled JavaScript version from leaking everything into the global namespace.So since there’s no way to make something “leak” into the global namespace from the coffee-script side of things on purpose, you need to define your global variables as properties of the global object.
This means you need to do something like
window.foo = 'baz';, which handles the browser case, since there the global object is thewindow.Node.js
In Node.js there’s no
windowobject, instead there’s theexportsobject that gets passed into the wrapper that wraps the Node.js module (See: https://github.com/ry/node/blob/master/src/node.js#L321 ), so in Node.js what you would need to do isexports.foo = 'baz';.Now let us take a look at what it states in your quote from the docs:
This is obviously coffee-script, so let’s take a look into what this actually compiles to:
First it will check whether
exportsis defined, since trying to reference a non existent variable in JavaScript would otherwise yield an SyntaxError (except when it’s used withtypeof)So if
exportsexists, which is the case in Node.js (or in a badly written WebSite…) root will point toexports, otherwise tothis. So what’sthis?Using
.callon a function will bind thethisinside the function to the first parameter passed, in case of the browserthiswould now be thewindowobject, in case of Node.js it would be the global context which is also available as theglobalobject.But since you have the
requirefunction in Node.js, there’s no need to assign something to theglobalobject in Node.js, instead you assign to theexportsobject which then gets returned by therequirefunction.Coffee-Script
After all that explanation, here’s what you need to do:
This will declare our function
fooin the global namespace (whatever that happens to be).That’s all 🙂