开发者

Coffeescript wrapping files in a function

开发者 https://www.devze.com 2023-03-28 17:44 出处:网络
The coffeescript compiler is, for some reason, wrapping all of my .coffee files in a function when they are compiled. For example, 开发者_C百科if I have test.coffee:

The coffeescript compiler is, for some reason, wrapping all of my .coffee files in a function when they are compiled. For example, 开发者_C百科if I have test.coffee:

class TestClass
    constructor: (@value) ->

    printValue: () ->
        alert(@value)

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

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);

My simple html file won't work with this:

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

I haven't worked with much JS before, and I wouldn't doubt the coffee compiler, but is the way it should work? How


See my answer here on sharing jS code between files/modules. Also FYI the wrapper function is by design to prevent unintentional global variables. You can disable with by passing --bare to the coffee compiler command line tool, but it is a best practice with good reason.


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()
0

精彩评论

暂无评论...
验证码 换一张
取 消