Coffeescript wrapping files in a function(Coffeescript 在函数中包装文件)
问题描述
出于某种原因,coffeescript 编译器在编译时将我所有的 .coffee 文件包装在一个函数中.例如,如果我有 test.coffee:
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()
然后我得到 test.js:
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);
我的简单 html 文件不适用于此:
My simple html file won't work with this:
<html>
<head>
<script src="test.js"></script>
</head>
<body onload="printAValue()">
</body>
</html>
我以前没有使用过很多 JS,我不会怀疑咖啡编译器,但它应该是这样工作的吗?如何
I haven't worked with much JS before, and I wouldn't doubt the coffee compiler, but is the way it should work? How
推荐答案
永远不要在 HTML 中添加事件监听器.将它们添加到您的 JavaScript 中,最好在您定义事件处理程序的同一范围内.
Never add event listeners in HTML. Add them in your JavaScript, preferably in the same scope in which you define the event handler.
printAValue = () ->
test = new TestClass()
test.printValue()
document.body.addEventListener('load', printAValue, false)
如果您绝对需要将某些内容导出到全局范围,请导出到窗口对象:
If you absolutely need to export something to the global scope, export to the window object:
window.printAValue = () ->
test = new TestClass()
test.printValue()
这篇关于Coffeescript 在函数中包装文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Coffeescript 在函数中包装文件


基础教程推荐
- 悬停时滑动输入并停留几秒钟 2022-01-01
- Karma-Jasmine:如何正确监视 Modal? 2022-01-01
- 我什么时候应该在导入时使用方括号 2022-01-01
- 在 JS 中获取客户端时区(不是 GMT 偏移量) 2022-01-01
- 角度Apollo设置WatchQuery结果为可用变量 2022-01-01
- 响应更改 div 大小保持纵横比 2022-01-01
- 在for循环中使用setTimeout 2022-01-01
- 有没有办法使用OpenLayers更改OpenStreetMap中某些要素 2022-09-06
- 当用户滚动离开时如何暂停 youtube 嵌入 2022-01-01
- 动态更新多个选择框 2022-01-01