Reputation: 191
I have created a Util API's to create function object and to invoke its function API's
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);
}
This Util API's work for below code:
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.
How to use FunctionUtils.invokeAndInflate API for more than one parameters ? ?
Upvotes: 3
Views: 4050
Reputation: 22478
You can rewrite the FunctionUtils.invokeAndInflate
function as below:
FunctionUtils.invokeAndInflate = function(object, functionName, parameterValue) {
object[functionName].apply(object, Array.prototype.slice.call(arguments, 2));
}
Upvotes: 4
Reputation: 12040
I suggest you reading about .call() and .apply(), here is an article about them. http://odetocode.com/blogs/scott/archive/2007/07/05/function-apply-and-function-call-in-javascript.aspx
Upvotes: 0