0

I have a function names in array in WSH Jscript, I need to call them in a loop. Al what I found is here Javascript - Variable in function name, possible? but this doesn't work, maybe because I use WSH and/or run the script from console, not browser.

var func = [
    'cpu'
];

func['cpu'] = function(req){
    WScript.Echo("req="+req);
    return "cpu";
}

for (var item in func) {
    WScript.Echo("item="+ func[item](1));
}

The result is:

C:\test>cscript b.js
Microsoft (R) Windows Script Host Version 5.6
Copyright (C) Microsoft Corporation 1996-2001. All rights reserved.

C:\test\b.js(11, 2) Microsoft JScript runtime error: Function expected

(this is WScript.Echo line)

So, is there any way to call function using name in variable in this environment?

Community
  • 1
  • 1
Putnik
  • 5,925
  • 7
  • 38
  • 58

1 Answers1

2

No, the problem is not WSH not command line.

This is what you have in your code:

var func = [
    'cpu'
];

that is, an array with one element in it. The content of the element is 'cpu' and its index is 0. Array length is 1.

func['cpu'] = function(req){
    WScript.Echo("req="+req);
    return "cpu";
}

This adds an aditional property to the array object not one element to the array content. If you test, array length is still 1.

for (var item in func) {
    WScript.Echo("item="+ func[item](1));
}

This iterates over the content of the array. item retrieves the index of each element in the array and then is used to retrieve the content. But the content of the array is only one element, with index 0 and its contents is a string (cpu). It is not a function, so, you can not call it.

The problem is you are mixing the way to work with objects and the way to work with arrays.

For an array version

var func = [
    function cpu(req){
        return 'called cpu('+req+')';
    },
    function other(req){
        return 'called other('+req+')';
    }
];

func.push(
    function more(req){
        return 'called more('+req+')';
    }
);

for (var item in func) {
    WScript.Echo('calling func['+item+']='+ func[item](1));
};

For a objects version

var func = {
    cpu : function(req){
        return 'called cpu('+req+')';
    },
    other : function(req){
        return 'called other('+req+')';
    }
};

func['more'] = function(req){
    return 'called more('+req+')';
};

for (var item in func) {
    WScript.Echo('calling func['+item+']='+ func[item](1));
};

As you can see, very similar, but if you work with arrays, then you should add elements to the array, not properties, as the for in will iterate over the elements in the array. In the case of the object approach, you add properties to an object and the for in iterates over the properties of the object.

Very similar, but not the same.

MC ND
  • 69,615
  • 8
  • 84
  • 126