如何在jquery/javascript中使用循环创建方法 [英] How to create methods with a loop in jquery/javascript

查看:53
本文介绍了如何在jquery/javascript中使用循环创建方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

尝试注册在循环中创建的某些方法时遇到问题.

I'm having problems trying to register some methods I've created in a loop inside an object.

我现在所拥有的是

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

It's working and do its job, but I want to be able to reach every method I've created through the loop in this way: console.log(ui.one());

而且我不会做类似的事情,因为如果这样做的话:

And I don't how to do something like that since if I do this:

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());访问...

then I can access through console.log(ui.one()); with no problem...

我想念什么?迭代它们时,有什么我不知道的方法注册方法吗?

What am I missing? Is there some way I don't know on registering the method when you iterate them?

推荐答案

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

scope.name refers the the name property on scope. If you want to access a property based on a string value, you need to use square bracket notation:

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

这篇关于如何在jquery/javascript中使用循环创建方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆