gpt4 book ai didi

javascript - 无法在文件外访问 coffeescript 函数

转载 作者:行者123 更新时间:2023-12-02 07:34:54 25 4
gpt4 key购买 nike

我正在尝试设置一个服务来对远程服务器执行 json 请求。

我在我的 services.coffee 脚本中使用这段代码:

HttpService = () ->

initialize: ->
__Model.List.destroyAll()
__Model.Item.destroyAll()

$$.get 'http://localhost:3000/lists.json', null, ((response) ->
lists = response.lists
items = response.items

$$.each lists, (i, list) ->
__Model.List.create list

$$.each items, (i, item) ->
__Model.Item.create item
), 'json'

createList: (list) ->
$$.post 'http://localhost:3000/lists.json', list, ((response) ->
), 'json'

http = new HttpService
http.initialize()

初始化方法工作正常。

我希望能够从我项目中的任何地方访问变量 http

但是,我无法访问此文件之外的函数。

如何全局定义它?

更新

这是 CoffeeScript 生成的文件

// Generated by CoffeeScript 1.6.3
(function() {
var HttpService, http;

HttpService = function() {
return {
initialize: function() {
__Model.List.destroyAll();
__Model.Item.destroyAll();
return $$.get('http://localhost:3000/lists.json', null, (function(response) {
var items, lists;
lists = response.lists;
items = response.items;
$$.each(lists, function(i, list) {
return __Model.List.create(list);
});
return $$.each(items, function(i, item) {
return __Model.Item.create(item);
});
}), 'json');
},
createList: function(list) {
return $$.post('http://localhost:3000/lists.json', list, (function(response) {}), 'json');
}
};
};

http = new HttpService;

http.initialize();

}).call(this);

最佳答案

那是因为 coffeescript 将代码包装在 top-level function safety wrapper 中.

在浏览器中,您可以通过以下方式使其成为全局:

window.http = http

或者通过编译-b告诉coffeescript不要做包装器:

coffee -c -b services.coffee

一般来说,全局变量不是一个好主意,您可能需要考虑使用像 require.js 这样的模块系统。组织和访问您的代码(包括不同文件中的代码)。

关于javascript - 无法在文件外访问 coffeescript 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17706711/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com