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="dGVzdC5qcw=="></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 在函数中包装文件


- 如何调试 CSS/Javascript 悬停问题 2022-01-01
- 为什么悬停在委托事件处理程序中不起作用? 2022-01-01
- 如何显示带有换行符的文本标签? 2022-01-01
- 我不能使用 json 使用 react 向我的 web api 发出 Post 请求 2022-01-01
- 从原点悬停时触发 translateY() 2022-01-01
- 为什么我的页面无法在 Github 上加载? 2022-01-01
- 使用 iframe URL 的 jQuery UI 对话框 2022-01-01
- 是否可以将标志传递给 Gulp 以使其以不同的方式 2022-01-01
- 如何向 ipc 渲染器发送添加回调 2022-01-01
- 在不使用循环的情况下查找数字数组中的一项 2022-01-01