从控制台调用 CoffeeScript 函数
尝试一下 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
共享全局方法/变量的一种更简单的方法是使用@,这意味着这个。
更好的语法和更容易阅读,但我不鼓励你创建全局方法/变量
an easier way to share global methods/variables is to use @ which means this.
Nicer syntax and easier to read, but I don't encourage you to create global methods/variables
发生这种情况是因为 CoffeeScript 将所有内容都包装在闭包中。该代码的 JavaScript 输出实际上是:
如果您想将其导出到全局范围,您可以执行以下操作:
或
This happens because coffeescript wraps everything in a closure. The JavaScript output of that code is actually:
If you want to export it to the global scope, you can either do:
or
我不确定 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.
此链接可能会解决您的问题
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