Coffeescript在一个函数中包装文件 [英] Coffeescript wrapping files in a function
问题描述
由于某种原因,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()
get 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在一个函数中包装文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!