Coffeescript 在函数中包装文件 [英] Coffeescript wrapping files in a function

查看:14
本文介绍了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()

这篇关于Coffeescript 在函数中包装文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆