0

我在服务器端有一个变量,该变量根据来自客户端的请求而变化,该请求确定要使用的函数。该函数看起来彼此相似,只是它开始调用不同的函数。因此,我在考虑是否可以用变量替换函数名称。

我在想的例子:

sortFunction = req.body.sortValue

path.sortFunction arg1, arg2, (callback) -> if err ... else ...

4

1 回答 1

2

您始终可以Object通过名称访问任何 JavaScript/CoffeeScript 的属性:

# suppose you have an object, that contains your sort functions
sortFunctions =
  quickSort: (a, b, cb) -> ...
  bubbleSort: (a, b, cb) -> ...
  insertionSort: (a, b, cb) -> ...

# you can access those properties of sortFunction
# by using the [] notation

sortFunctionName = req.body.sortValue
sortFunction = sortFunctions[sortFunctionName]

# this might return no value, when 'sortFunctionName' is not present in your object
# you can compensate that by using a default value
sortFunction ?= sortFunctions.quickSort

# now use that function as you would usually do
sortFunction arg1, arg2, (err, data) -> if err ... else ...

希望有帮助;)

于 2013-01-11T08:54:43.417 回答