Calling coffeescript functions from console

前端 未结 4 976
南旧
南旧 2020-12-29 07:30

Playing a little with coffeescript and Rails 3.1.0.rc4. Have this code:

yourMom = (location) ->
  console.log location

yourMom \"wuz hur\"
相关标签:
4条回答
  • 2020-12-29 08:03

    an easier way to share global methods/variables is to use @ which means this.

    @yourMom = (location) ->
      console.log location
    
    yourMom "wuz hur"
    

    Nicer syntax and easier to read, but I don't encourage you to create global methods/variables

    0 讨论(0)
  • 2020-12-29 08:06

    This happens because coffeescript wraps everything in a closure. The JavaScript output of that code is actually:

    (function() {
      var yourMom;
      yourMom = function(location) {
        return console.log(location);
      };
      yourMom("wuz hur");
    }).call(this);
    

    If you want to export it to the global scope, you can either do:

    window.yourMom = yourMom = (location) ->
      console.log location
    

    or

    this.yourMom = yourMom = (location) ->
      console.log location
    
    0 讨论(0)
  • 2020-12-29 08:18

    I'm not sure about Rails but the CoffeeScript compiler has an option (--bare) to compile without the function wrapper. Fine for playing but it does pollute the global scope.

    0 讨论(0)
  • 2020-12-29 08:22

    this link might solve your problem Rails - Calling CoffeeScript from JavaScript Wrap your functions in a unique namespace and then you can acess these functions from wnywhere

    0 讨论(0)
提交回复
热议问题