javascript 从控制台调用咖啡脚本函数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6756044/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 21:44:34  来源:igfitidea点击:

Calling coffeescript functions from console

javascriptcoffeescriptruby-on-rails-3.1

提问by Lee Quarella

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

玩一些 Coffeescript 和 Rails 3.1.0.rc4。有这个代码:

yourMom = (location) ->
  console.log location

yourMom "wuz hur"

When the page loads, this outputs "wuz hur" properly. But when I try to call

当页面加载时,这会正确输出“wuz hur”。但是当我尝试打电话时

yourMom("wuz hur")

from the chrome js console (as I do sometimes to test normal JS functions), I get a "ReferenceError: yourMom is not defined"

从 chrome js 控制台(我有时会测试普通的 JS 功能),我得到一个“ReferenceError: yourMom is not defined”

Are functions generated by coffeescript available in this way?

由咖啡脚本生成的函数是否可用这种方式?

回答by Sébastien Gruhier

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

更好的语法和更容易阅读,但我不鼓励你创建全局方法/变量

回答by Jamie Wong

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

发生这种情况是因为 coffeescript 将所有内容都包装在一个闭包中。该代码的 JavaScript 输出实际上是:

(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

回答by liammclennan

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.

我不确定 Rails,但 CoffeeScript 编译器有一个选项 (--bare) 可以在没有函数包装器的情况下进行编译。很好玩,但它确实污染了全局范围。

回答by sajesh Nambiar

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

此链接可能会解决您的问题 Rails - Calling CoffeeScript from JavaScript将您的函数包装在一个唯一的命名空间中,然后您就可以从 wnywhere 访问这些函数