Coffeescript 在函数中包装文件

2022-01-24 00:00:00 javascript 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()

相关文章