我正在努力找出在ColdFusion 9中调用动态方法的正确<cfscript>语法。我已经尝试了许多变体,并进行了很好的搜索。
<cfinvoke>显然是我想要的标签,但遗憾的是我不能在我的纯cfscript组件中使用它,因为它是在ColdFusion 10中实现的。
即coldfusion 9 dynamically call method
我已经在我的CFC中尝试了以下几种方法:
/** Validate the method name **/
var resources = getResources();
if (structKeyExists(variables.resources, name)) {
variables.resourceActive[name] = true;
var reflectionMethod = resources[name];
var result = "#reflectionMethod.getMethodName()#"(argumentCollection = params);
}其中reflectionMethod.getMethodName()的返回值是我要调用的方法名。它100%返回正确的值(方法的名称),其中该方法被正确定义并可访问,
我的错误是该行上的语法错误。
发布于 2012-09-28 07:30:23
你不想得到方法名,你想要得到实际的方法,例如:
function getMethod(string method){
return variables[method];
}调用,因此:
theMethod = getMethod(variableHoldingMethodName);
result = theMethod();不幸的是,人们不能简单地这样做:
result = getMethod(variableFoldingMethodName)();或者:
result = myObject[variableFoldingMethodName]();因为CF解析器不喜欢将括号或括号放在一起。
我所建议的方法需要注意的是,它将方法从CFC中拉出,因此它将在调用代码的上下文中运行,而不是在CFC实例中运行。根据方法中的代码,这可能重要也可能无关紧要。
另一种选择是将静态命名的方法注入到对象中,例如:
dynamicName = "foo"; // for example
myObject.staticName = myObject[dynamicName];
result = myObject.staticName(); // is actually calling foo();发布于 2012-09-28 07:13:34
假设该方法在您当前的(变量)作用域中,您可以尝试:
var result = variables[reflectionMethod.getMethodName()](argumentCollection = params);https://stackoverflow.com/questions/12631347
复制相似问题