我创建了一个Util 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用于多个参数? ?
答案 0 :(得分:4)
您可以重写FunctionUtils.invokeAndInflate
功能,如下所示:
FunctionUtils.invokeAndInflate = function(object, functionName, parameterValue) {
object[functionName].apply(object, Array.prototype.slice.call(arguments, 2));
}
答案 1 :(得分:0)
我建议您阅读.call()和.apply(),这是一篇关于它们的文章。 http://odetocode.com/blogs/scott/archive/2007/07/05/function-apply-and-function-call-in-javascript.aspx