質問

I have a function like this.

function myfun(input1, input2, input3){
    //
    // Other codes which deals with input2 and input3 (irrelevant)
    //
    function a(){
        console.log('func a');
    }
    function b(){
        console.log('func b');
    }
    function c(){
        console.log('func c');
    }
    function d(){
        console.log('func d');
    }
    // input1 is an array
    for(var i=0; i<input1.length; i++){
        var name = input1[i];
        name(); // Doesn't work as 'name' refers to a string;
        this[name](); // Doesn't work;
        // How can i execute the nested function whose name is stored in input array ?
    }
}
myfun(['b','d'], 'foo', 'bar');

How can I call the nested functions whose names are given in input1 array?

Thank You.

役に立ちましたか?

解決

Edit

As @Felix suggested, there is a much better way (in terms of efficiency) to do this -

var myfun = (function () {
    var util = {
        a: function (){
            console.log('method a');
        },
        b: function (){
            console.log('method b');
        },
        c: function (){
            console.log('method c');
        },
        d: function (){
            console.log('method d');
        }
    };

    return function (input1, input2, input3) {
        for(var i=0; i<input1.length; i++){
            var name = input1[i];
            util[name]();
        }
    };
}());

myfun(['b','d'], 'foo', 'bar');

This way the util object will be constructed only once, where in the previous way the object will be constructed each time myfun is called.

However, please note that in this case, the memory footprint will be larger than the previous one as a reference to util will always be stored in the memory because of closure.


Rather than creating inner functions, try creating an object with methods -

function myfun(input1, input2, input3){
    var util = {
        a: function (){
            console.log('method a');
        },
        b: function (){
            console.log('method b');
        },
        c: function (){
            console.log('method c');
        },
        d: function (){
            console.log('method d');
        }
    };

    for(var i=0; i<input1.length; i++){
        var name = input1[i];
        util[name]();
    }
}

myfun(['b','d'], 'foo', 'bar');

他のヒント

replace the name(); with eval(name + '()');

EDITED:

You must make the functions members of an object.

var funcFactory = {
    a:function(){
        console.log('func a');
    },
    b:function(){
        console.log('func b');
    },
    c:function(){
        console.log('func c');
    },
    d:function(){
        console.log('func d');
    },
    call:function(input1, input2, input3){     
        for(var i=0; i<input1.length; i++){
           var name = input1[i];
            this[name](); // Doesn't work;
        }
    }
}
funcFactory.call(['b','d'],foo,bar);
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top