使用coffeescript在服务器端的变量中调用其名称的一部分

时间:2013-01-11 08:35:09

标签: function variables coffeescript server-side server-side-scripting

我在服务器端有一个变量,它根据来自客户端的请求而改变,该请求决定使用哪个函数。除了启动对不同函数的调用之外,该函数看起来彼此相似。因此,我在想是否可以用变量替换函数名。

我在想的例子:

sortFunction = req.body.sortValue

path.sortFunction arg1,arg2,(callback) - >     如果错了         ...     其他         ...

1 个答案:

答案 0 :(得分:2)

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

# 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 ...

希望有所帮助;)