Coffeescript 将文件包装在函数中
由于某种原因,coffeescript 编译器在编译时将所有 .coffee 文件包装在一个函数中。例如,如果我有 test.coffee:
class TestClass
constructor: (@value) ->
printValue: () ->
alert(@value)
printAValue = () ->
test = new TestClass()
test.printValue()
那么我得到 test.js:
(function() {
var TestClass, printAValue;
TestClass = (function() {
function TestClass(value) {
this.value = value;
}
TestClass.prototype.printValue = function() {
return alert(this.value);
};
return TestClass;
})();
printAValue = function() {
var test;
test = new TestClass();
return test.printValue();
};
}).call(this);
My simple html file won't work with this:
<html>
<head>
<script src="test.js"></script>
</head>
<body onload="printAValue()">
</body>
</html>
我以前没有使用过太多 JS,我不会怀疑咖啡编译器,但是它应该如何运作?如何
The coffeescript compiler is, for some reason, wrapping all of my .coffee files in a function when they are compiled. For example, if I have test.coffee:
class TestClass
constructor: (@value) ->
printValue: () ->
alert(@value)
printAValue = () ->
test = new TestClass()
test.printValue()
then I get test.js:
(function() {
var TestClass, printAValue;
TestClass = (function() {
function TestClass(value) {
this.value = value;
}
TestClass.prototype.printValue = function() {
return alert(this.value);
};
return TestClass;
})();
printAValue = function() {
var test;
test = new TestClass();
return test.printValue();
};
}).call(this);
My simple html file won't work with this:
<html>
<head>
<script src="test.js"></script>
</head>
<body onload="printAValue()">
</body>
</html>
I haven't worked with much JS before, and I wouldn't doubt the coffee compiler, but is the way it should work? How
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
请参阅我的回答关于在文件/模块之间共享js代码。另外仅供参考,包装函数的设计目的是防止意外的全局变量。您可以通过将
--bare
传递给咖啡编译器命令行工具来禁用 with,但这是有充分理由的最佳实践。See my answer here on sharing jS code between files/modules. Also FYI the wrapper function is by design to prevent unintentional global variables. You can disable with by passing
--bare
to the coffee compiler command line tool, but it is a best practice with good reason.切勿在 HTML 中添加事件侦听器。将它们添加到您的 JavaScript 中,最好在您定义事件处理程序的同一范围内。
如果您绝对需要将某些内容导出到全局范围,请导出到 window 对象:
Never add event listeners in HTML. Add them in your JavaScript, preferably in the same scope in which you define the event handler.
If you absolutely need to export something to the global scope, export to the window object: