如何使用jquery / javascript中的循环创建方法

我在尝试注册我在对象内的循环中创建的一些方法时遇到了问题。

我所拥有的是这样的:

var scriptList = { components : [ 'all' ], modules : [ 'one', 'two', 'three' ] } function interface() { var scope = this; jQuery.each(scriptList, function(key, value) { jQuery.each(value, function (index, name) { var hookValue = 'hook_'+name; scope.name = function(){ window[hookValue] = jQuery('.js-'+name); loadAndUse(window[hookValue],key+'/'+name); } if(key === 'modules'){ scope.name(); } }); }); } var ui = new interface(); 

它正在工作并完成它的工作,但我希望能够以这种方式通过循环创建我创建的每个方法: console.log(ui.one());

如果我这样做,我不会怎么做这样的事情:

 function interface() { var scope = this; scope.one = function(){ console.log('one'); } scope.two = function(){ console.log('two'); } scope.three = function(){ console.log('three'); } } 

然后我可以通过console.log(ui.one()); 没问题……

我错过了什么? 在迭代它们时,有什么方法我不知道注册方法吗?

scope.name引用scope上的name属性。 如果要基于字符串值访问属性,则需要使用方括号表示法:

 scope[name] = function(){ window[hookValue] = jQuery('.js-'+name); loadAndUse(window[hookValue],key+'/'+name); }