在 Coffeescript.org 上:
bawbag = (x, y) ->
z = (x * y)
bawbag(5, 10)
将编译为:
var bawbag;
bawbag = function(x, y) {
var z;
return (z = (x * y));
};
bawbag(5, 10);
在 node.js 下通过 coffee-script 编译会这样包装:
(function() {
var bawbag;
bawbag = function(x, y) {
var z;
return (z = (x * y));
};
bawbag(5, 10);
}).call(this);
文档说:
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
我如何在 CoffeeScript 中定义全局变量。 '将它们作为属性附加到窗口'是什么意思?
最佳答案
由于 CoffeeScript 没有 var
语句,它会自动将它插入到 CoffeeScript 中的所有变量中,这样可以防止编译后的 JavaScript 版本将所有内容泄漏到 全局命名空间强>。
因此,由于没有办法故意从 CoffeeScript 方面“泄漏”到 全局命名空间 中,因此您需要将全局变量定义为 的属性全局对象。
attach them as properties on window
这意味着您需要执行类似 window.foo = 'baz';
之类的操作,它会处理浏览器的情况,因为那里的 全局对象 就是 窗口
.
Node.js
在 Node.js 中没有 window
对象,取而代之的是 exports
对象,它被传递到包装 Node.js 模块的包装器中(参见:https://github.com/ry/node/blob/master/src/node.js#L321 ),所以在 Node.js 中你需要做的是 exports.foo = 'baz';
.
现在让我们来看看它在您引用的文档中所说的内容:
...targeting both CommonJS and the browser: root = exports ? this
这显然是coffee-script,所以让我们看看它实际编译成什么:
var root;
root = (typeof exports !== "undefined" && exports !== null) ? exports : this;
首先它会检查是否定义了 exports
,因为试图在 JavaScript 中引用一个不存在的变量会产生一个 SyntaxError(除非它与 typeof
一起使用)
所以如果 exports
存在,在 Node.js 中就是这种情况(或者在一个写得不好的网站......)根将指向 exports
,否则指向 这个
。那么这个
是什么?
(function() {...}).call(this);
在函数上使用 .call
会将函数内部的 this
绑定(bind)到传递的第一个参数,如果浏览器 this
会现在是 window
对象,如果是 Node.js,它将是 global context,它也可用作 global
对象。
但是由于您在 Node.js 中有 require
函数,因此无需为 Node.js 中的 global
对象分配某些内容,而是分配给 exports
对象,然后由 require
函数返回。
CoffeeScript
在所有这些解释之后,这就是你需要做的:
root = exports ? this
root.foo = -> 'Hello World'
这将在全局命名空间中声明我们的函数 foo
(无论发生什么)。
就是这样:)
关于javascript - 如何在 CoffeeScript 中定义全局变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4214731/