0

サーバー側に、使用する関数を決定するクライアント側からの要求に応じて変化する変数があります。この関数は、別の関数の呼び出しを開始することを除いて、互いに似ています。そのため、関数名を変数に置き換えることができないかと考えていました。

私が考えていることの例:

sortFunction = req.body.sortValue

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

4

1 に答える 1

2

ObjectJavaScript/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 に答える