Coffeescript在函数中包装文件

Coffeescript wrapping files in a function

本文关键字:包装 文件 函数 Coffeescript      更新时间:2023-09-26

由于某种原因,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);

我的简单的html文件不能工作:

<html>
    <head>
        <script src="test.js"></script>
    </head>
    <body onload="printAValue()">
    </body>
</html>

我以前没有使用过太多的JS,我不会怀疑咖啡编译器,但它应该工作的方式吗?如何

关于在文件/模块之间共享jS代码,请参阅我的回答。另外,包装器函数的设计是为了防止无意的全局变量。您可以通过将--bare传递给coffee编译器命令行工具来禁用它,但这是一个有充分理由的最佳实践。

永远不要在HTML中添加事件侦听器。将它们添加到JavaScript中,最好与定义事件处理程序的作用域相同。

printAValue = () -> 
    test = new TestClass()
    test.printValue()
document.body.addEventListener('load', printAValue, false)

如果你绝对需要导出一些东西到全局作用域,导出到window对象:

window.printAValue = () -> 
    test = new TestClass()
    test.printValue()