简体   繁体   English

如何在多个文件中创建JS对象

[英]How to make a JS object available across multiple files

I'm a js noob working on a Rails app. 我是一个使用Rails应用程序的js noob。 I defined a useful JS function in one of my javascript files, and I'd like it to be available to call in other files. 我在我的一个javascript文件中定义了一个有用的JS函数,我希望它可以在其他文件中调用。 However, it's not. 但事实并非如此。 Here's a simplified example of my situation... note that I'm using CoffeeScript (but AFAIK that should make no difference): 这是我的情况的简化示例...请注意,我使用的是CoffeeScript(但AFAIK应该没有区别):

#file: app/assets/javascripts/foos.js.coffee
testFoo: ->
  alert 'Foo'

#file: app/assets/javascripts/bars.js.coffee
jQuery ->
  testFoo()

This doesn't work, and in the console I get: testFoo is not defined . 这不起作用,在控制台中我得到: testFoo is not defined

Both files are included in the page, if I put an alert or console log in either one the page responds as expected. 这两个文件都包含在页面中,如果我将警报或控制台日志放入其中任何一个页面,则按预期响应。 I feel like I must be overlooking something brutally obvious here... what is it? 我觉得我必须忽略一些残酷的东西......这是什么?

In short try this : 总之试试这个:

root = exports ? this
root.foo = -> alert 'Foo'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM