gpt4 book ai didi

javascript - 从 Javascript 类对象返回函数

转载 作者:行者123 更新时间:2023-12-03 07:09:12 25 4
gpt4 key购买 nike

我已经用这种风格模块化了我的 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];

关于javascript - 从 Javascript 类对象返回函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36683817/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com