jdog jdog - 1 year ago 55
Javascript Question

return function from Javascript class object

I have modularized my Javascript code in this style:

var groupHandler = function( constructorOptions )
{
"use strict";

var init = function( optionsToSet )
{
jQuery.extend( options, optionsToSet);
return this;
};


var newGroup = function()
{

}

var call = {
init: init,
options: options,
newGroup: newGroup
};

if(typeof myPublicTestNamespace == "undefined"){//http://stackoverflow.com/a/9172377/123594
return {
init: init,
newGroup: newGroup
};
}else{
return call;
};

init( constructorOptions );
};


In one of my modules I have a list of functions from other modules to call like this:

validatorFunctions = call.getLocalStorageArray( 'validatorFunctions', model);
for (var f=0;f < validatorFunctions.length;f++){
if (callFunction = call.getFunction( validatorFunctions[f] )){
valid = callFunction( loopRowId, fields, call );
if (!valid) break;
}
}


I'd like to be able to call functions in other modules by using a "." syntax in my function call name:

var getFunction = function( functionName )
{
if (functionName.indexOf( '.' ) != -1){
var functionParts = functionName.split( '.' );
var classFunction = functionParts[1];
if (typeof window[functionParts[0]] === "function") {
var obj = new window[functionParts[0]]();
return obj['classFunction']; <!----- how to return function here?
}
}else{
if (typeof (window[functionName]) === "function") {
return window[functionName];
}
}
return false;
};


but I can't figure out how to return the function based on the class object and the function name?

JMM JMM
Answer Source

It's possible that part or all of the problem is this:

return obj['classFunction'];

// ^^ Equivalent to obj.classFunction. In other words, reading a property
// called `classFunction`, not reading a property whose name is the value
// of the `classFunction` variable you set.

I haven't analyzed the code enough to fully understand it, but based on the context it seems that you'd mean this:

return obj[classFunction];