【问题标题】:Coffeescript wrapping files in a functionCoffeescript 在函数中包装文件
【发布时间】:2011-10-28 06:48:30
【问题描述】:

出于某种原因,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,我不会怀疑咖啡编译器,但它应该是这样工作的吗?如何

【问题讨论】:

标签: javascript coffeescript


【解决方案1】:

请参阅my answer here 在文件/模块之间共享 jS 代码。仅供参考,包装函数是设计用来防止无意的全局变量的。您可以通过将 --bare 传递给咖啡编译器命令行工具来禁用 with,但这是有充分理由的最佳实践。

【讨论】:

    【解决方案2】:

    永远不要在 HTML 中添加事件监听器。将它们添加到您的 JavaScript 中,最好在您定义事件处理程序的同一范围内。

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

    如果您绝对需要将某些内容导出到全局范围,请导出到窗口对象:

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

    【讨论】:

    • 好的,感谢您解决了这个问题。但是现在我遇到了一个问题,如果我在我的 HTML 中包含多个 js 文件,它们将无法访问彼此的类。那是因为它们都被定义在某个非全局范围内,而这就是我要寻找它们的地方吗?
    • 是的,它们都封装在一个函数中。创建一些全局命名空间对象 (window.NS = {}) 并将您的类导出到该命名空间 (NS.TestClasses = TestClasses)。命名空间将可跨文件全局访问。
    • 你也可以把printAValue: -&gt;替换成this.printAValue: -&gt;,如果你仔细看的话,这和window.printAValue: -&gt;是一样的。 :-)
    猜你喜欢
    • 1970-01-01
    • 2013-08-08
    • 1970-01-01
    • 2019-10-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-31
    相关资源
    最近更新 更多