2013-05-13 125 views
3

我已经创建了一个实用程序的API来创建函数对象并调用其API函数的如何动态地将多个参数传递给函数?

function FunctionUtils() { 

} 

FunctionUtils.createFunctionInstance = function(functionName) { 
    var obj = FunctionUtils.createFunctionInstanceDescend(window, functionName); 
    return new obj(); 
} 

FunctionUtils.createFunctionInstanceDescend = function(obj, path) { 
    var parts = path.split('.'); 

    for(var i = 0; i < parts.length; i++) { 
     obj = obj[parts[i]]; 
    } 

    return obj; 
} 


FunctionUtils.invokeAndInflate = function(object, functionName, parameterValue) { 
    object[functionName](parameterValue); 
} 

此的Util API的工作,为下面的代码:

function Student() { 

    var firstName; 

    var city, country; 

    this.getFirstName = function() { 
      return firstName; 
    } 

    this.setFirstName = function(val) { 
      firstName = val; 
    } 

    this.getAddress() { 
      return city + country; 
    } 

    this.setAddress(val1, val2) { 
      city = val1; 
      country = val2; 
    } 

} 


var student = FunctionUtils.createFunctionInstance("Student"); 
FunctionUtils.invokeAndinflate(student, "setFirstName", "Pranav"); //Works 

FunctionUtils.invokeAndInflate(student, "setAddress", "LA", "USA"); //Doesn't Work. 

如何使用FunctionUtils.invokeAndInflate API超过一个参数? ?

回答

3

可以改写为以下FunctionUtils.invokeAndInflate功能:

FunctionUtils.invokeAndInflate = function(object, functionName, parameterValue) { 
    object[functionName].apply(object, Array.prototype.slice.call(arguments, 2)); 
} 
+0

您可以从函数调用下降的参数,如果你想,从'arguments'让他们所有。最后一个至少应该被删除。 – 2013-05-13 13:45:01

相关问题