从控制台调用 CoffeeScript 函数

发布于 2024-11-25 07:19:53 字数 349 浏览 0 评论 0原文

尝试一下 CoffeeScript 和 Rails 3.1.0.rc4。有这样的代码:

yourMom = (location) ->
  console.log location

yourMom "wuz hur"

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

yourMom("wuz hur")

从 chrome js 控制台调用时(就像我有时测试普通 JS 函数一样),我得到一个“ReferenceError:yourMom 未定义”

由 Coffeescript 生成的函数是否可以通过这种方式使用?

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

yourMom = (location) ->
  console.log location

yourMom "wuz hur"

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

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"

Are functions generated by coffeescript available in this way?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

不如归去 2024-12-02 07:19:53

共享全局方法/变量的一种更简单的方法是使用@,这意味着这个。

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

yourMom "wuz hur"

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

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

向日葵 2024-12-02 07:19:53

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

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

如果您想将其导出到全局范围,您可以执行以下操作:

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

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

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
心不设防 2024-12-02 07:19:53

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

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.

╰つ倒转 2024-12-02 07:19:53

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

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文