3

我创建了一个 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 用于多个参数??

4

2 回答 2

4

你可以重写FunctionUtils.invokeAndInflate函数如下:

FunctionUtils.invokeAndInflate = function(object, functionName, parameterValue) {
    object[functionName].apply(object, Array.prototype.slice.call(arguments, 2));
}
于 2013-05-13T13:39:16.387 回答
0

我建议您阅读有关 .call() 和 .apply() 的内容,这里有一篇关于它们的文章。 http://odetocode.com/blogs/scott/archive/2007/07/05/function-apply-and-function-call-in-javascript.aspx

于 2013-05-13T13:16:45.080 回答