如何在 coffeesricpt 中将一个函数从一个模块导出到另一个模块?
How to export a function from a module to another in coffeesricpt?
出于代码重用的目的,我想在单个函数中捕获一些逻辑并在其他模块中调用它
这是函数定义
// Module A
define (require) ->
doSomething(a, b, c) ->
"#{a}?#{b}&#{c}"
下面是函数 doSomething
的用法
// Module B
define(require) ->
a = require 'A'
...
class Bee
constructor: ->
@val = a.doSomething(1, 2, 3)
但是在浏览器中,我收到了这个错误信息
Uncaught ReferenceError: doSomething is not defined
在 coffeescript 中 export/import 免费函数的正确方法是什么?
这个:
define (require) ->
doSomething(a, b, c) ->
"#{a}?#{b}&#{c}"
不是函数定义。原来是这样变相的:
define (require) ->
return doSomething(a, b, c)( -> "#{a}?#{b}&#{c}")
所以你的模块试图调用 doSomething
函数,然后调用它 return 作为另一个函数,该函数将第三个函数作为参数。然后从模块发回任何 doSomething(...)(...)
returns。
所以当你这样说时:
a = require 'A'
你在 a
中得到 "who knows what" 而那个东西没有 doSomething
属性 所以 a.doSomething(1,2,3)
给你 ReferenceError
.
我认为您想将函数包装在模块中的一个对象中:
define (require) ->
doSomething: (a, b, c) ->
"#{a}?#{b}&#{c}"
或者,您可以 return 函数:
define (require) ->
(a, b, c) ->
"#{a}?#{b}&#{c}"
然后像这样使用它:
doSomething = require 'A'
doSomething(1, 2, 3)
出于代码重用的目的,我想在单个函数中捕获一些逻辑并在其他模块中调用它
这是函数定义
// Module A
define (require) ->
doSomething(a, b, c) ->
"#{a}?#{b}&#{c}"
下面是函数 doSomething
的用法
// Module B
define(require) ->
a = require 'A'
...
class Bee
constructor: ->
@val = a.doSomething(1, 2, 3)
但是在浏览器中,我收到了这个错误信息
Uncaught ReferenceError: doSomething is not defined
在 coffeescript 中 export/import 免费函数的正确方法是什么?
这个:
define (require) ->
doSomething(a, b, c) ->
"#{a}?#{b}&#{c}"
不是函数定义。原来是这样变相的:
define (require) ->
return doSomething(a, b, c)( -> "#{a}?#{b}&#{c}")
所以你的模块试图调用 doSomething
函数,然后调用它 return 作为另一个函数,该函数将第三个函数作为参数。然后从模块发回任何 doSomething(...)(...)
returns。
所以当你这样说时:
a = require 'A'
你在 a
中得到 "who knows what" 而那个东西没有 doSomething
属性 所以 a.doSomething(1,2,3)
给你 ReferenceError
.
我认为您想将函数包装在模块中的一个对象中:
define (require) ->
doSomething: (a, b, c) ->
"#{a}?#{b}&#{c}"
或者,您可以 return 函数:
define (require) ->
(a, b, c) ->
"#{a}?#{b}&#{c}"
然后像这样使用它:
doSomething = require 'A'
doSomething(1, 2, 3)