我的要求是相变我必须构造方法名称并调用方法和后续方法,这里我能够构造方法名称,但它是String,不能调用方法。我已经遵循了一些建议,但我无法实现。请帮忙。
var previousPhase = $("#currentPhase").val();
var projectPhaseArray = ["requirement", "design", "construction", "testing", "release"];
var i = 0;
$("#currentPhase").change(function() {
alert(previousPhase);
i=projectPhaseArray.indexOf(previousPhase);
for (i; i < projectPhaseArray.length; i++) {
alert(projectPhaseArray[i]);
var phaseTimeLineToCall =
projectPhaseArray[i].concat("PhasePhaseTimeLines");
executeFunctionByName(phaseTimeLineToCall,window);
}
});
function executeFunctionByName(functionName, context /*, args */) {
return context[functionName].apply(context);
}
function requirementPhaseTimeLines(){
alert("In RequirementPhaseTimelines");
}
function designPhaseTimeLines(){
alert("In DesignPhaseTimelines");
}
感谢。
答案 0 :(得分:0)
字符串不会变异,因此您需要保存该值
projectPhaseArray[i] = projectPhaseArray[i].concat("PhasePhaseTimeLines");
答案 1 :(得分:0)
您可以使用javascript对象,将函数名称存储为键,将函数引用存储为值
var lookup = {
requirementPhaseTimeLines: requirementPhaseTimeLines,
designPhaseTimeLines: designPhaseTimeLines
}
我们必须稍微修改executeFunctionByName
function executeFunctionByName(functionName, lookup) {
return lookup[functionName]()
}
function requirementPhaseTimeLines() {
return "In RequirementPhaseTimelines"
}
function designPhaseTimeLines() {
return "In DesignPhaseTimelines"
}
var lookup = {
requirementPhaseTimeLines: requirementPhaseTimeLines,
designPhaseTimeLines: designPhaseTimeLines
}
function executeFunctionByName(functionName, lookup) {
return lookup[functionName]()
}
console.log(
executeFunctionByName("requirementPhaseTimeLines", functions)
)
console.log(
executeFunctionByName("designPhaseTimeLines", functions)
)
如果我们想传递参数,我们必须curry我们想要执行的函数。
function greet(word) {
return function(name) {
return word + ', ' + name + '.'
}
}
其次,我们必须创建一个函数,我们可以通过参数迭代并将每个arguement值设置为我们想要执行的函数:
function setArguments(functionRef, args) {
return args.length === 1
? functionRef
: setArguments(functionRef(args[0]), args.slice(1))
}
function greet(word) {
return function(name) {
return word + ', ' + name + '.'
}
}
var lookup = {
greet: greet
}
function getFunction(lookup, name) {
return lookup[name] || new Function()
}
function setArguments(functionRef, args) {
return args.length === 1
? functionRef
: setArguments(functionRef(args[0]), args.slice(1))
}
function executeFunctionByName(functionName, lookup, args) {
var functionRef = getFunction(lookup, functionName)
var functionRefWithArgs = setArguments(functionRef, args)
return functionRefWithArgs(args[args.length - 1])
}
console.log(
executeFunctionByName('greet', lookup, ['Hi', 'Jon'])
)