DrP*_*per 8 javascript coffeescript
出于某种原因,coffeescript编译器在编译时将所有.coffee文件包装在函数中.例如,如果我有test.coffee:
class TestClass
constructor: (@value) ->
printValue: () ->
alert(@value)
printAValue = () ->
test = new TestClass()
test.printValue()
Run Code Online (Sandbox Code Playgroud)
然后我得到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);
Run Code Online (Sandbox Code Playgroud)
我的简单html文件不适用于此:
<html>
<head>
<script src="test.js"></script>
</head>
<body onload="printAValue()">
</body>
</html>
Run Code Online (Sandbox Code Playgroud)
我之前没有使用过很多JS,我不会怀疑咖啡编译器,但它应该如何工作?怎么样
切勿在HTML中添加事件侦听器.将它们添加到JavaScript中,最好与定义事件处理程序的范围相同.
printAValue = () ->
test = new TestClass()
test.printValue()
document.body.addEventListener('load', printAValue, false)
Run Code Online (Sandbox Code Playgroud)
如果您绝对需要将某些内容导出到全局范围,请导出到窗口对象:
window.printAValue = () ->
test = new TestClass()
test.printValue()
Run Code Online (Sandbox Code Playgroud)