Coffeescript将文件包装在一个函数中

8
咖啡脚本编译器在编译所有的 .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,虽然我不怀疑咖啡编译器,但这样的工作方式是否正确呢?如何做到呢?


尝试将你的CoffeeScript代码行更改为向TestClass初始化程序传递一个值 - test = new TestClass('hello world') - arunkumar
请看我在 StackOverflow 上有关于在 JS 文件/模块之间共享代码的回答:链接 - Peter Lyons
这是关于CoffeeScript在SO上最受欢迎的问题。请参见https://dev59.com/YljUa4cB1Zd3GeqPTKFZ,https://dev59.com/42855IYBdhLWcg3wp2N0,https://dev59.com/3m025IYBdhLWcg3w960W... - Trevor Burnham
2个回答

9

请参考我的答案,了解在文件/模块之间共享JavaScript代码的方法。另外需要注意的是,包装函数的设计是为了防止意外创建全局变量。你可以通过向Coffee编译器命令行工具传递--bare来禁用它,但这是一种良好实践。


7
不要在HTML中添加事件监听器。在JavaScript中添加它们,最好是在定义事件处理程序的同一作用域内。
printAValue = () -> 
    test = new TestClass()
    test.printValue()

document.body.addEventListener('load', printAValue, false)

如果您确实需要将某些内容导出到全局作用域,请导出到window对象:
window.printAValue = () -> 
    test = new TestClass()
    test.printValue()

好的,谢谢您解决了那个问题。但现在我遇到了一个问题,如果我在HTML中包含多个js文件,它们不能访问彼此的类。这是因为它们都被定义在同一个非全局范围内吗?而我正在寻找它们的位置? - DrPepper
1
是的,它们都被封装在一个函数中。创建一些全局命名空间对象(window.NS = {}),并将你的类导出到该命名空间中(NS.TestClasses = TestClasses)。该命名空间将在文件之间全局访问。 - katspaugh
你也可以将 printAValue: -> 替换为 this.printAValue: ->,如果你仔细观察 this,这与 window.printAValue: -> 是相同的。:-) - MarkovCh1

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接