从Javascript类对象返回函数

return function from Javascript class object

本文关键字:返回 函数 对象 Javascript      更新时间:2023-09-26

我已经用这种风格模块化了我的Javascript代码:

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 );
};

在我的一个模块中,我有一个来自其他模块的函数列表,可以这样调用:

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;
    }
}

我希望能够通过在我的函数调用名称中使用"."语法来调用其他模块中的函数:

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;
};

但我不知道如何根据类对象和函数名返回函数?

部分或全部问题可能是:

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.

我还没有对代码进行足够的分析来完全理解它,但根据上下文,你的意思似乎是:

return obj[classFunction];