windows - Jscript - Variable in function name, possible? -
i have function names in array in wsh jscript, need call them in loop. al found here javascript - variable in function name, possible? doesn't work, maybe because use wsh and/or run script console, not browser.
var func = [ 'cpu' ]; func['cpu'] = function(req){ wscript.echo("req="+req); return "cpu"; } (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. rights reserved. c:\test\b.js(11, 2) microsoft jscript runtime error: function expected
(this wscript.echo line)
so, there way call function using name in variable in environment?
no, problem not wsh not command line.
this have in code:
var func = [ 'cpu' ];
that is, array 1 element in it. content of element 'cpu' , index 0. array length 1.
func['cpu'] = function(req){ wscript.echo("req="+req); return "cpu"; }
this adds aditional property array object not 1 element array content. if test, array length still 1.
for (var item in func) { wscript.echo("item="+ func[item](1)); }
this iterates on content of array. item
retrieves index of each element in array , used retrieve content. content of array 1 element, index 0 , contents string (cpu
). not function, so, can not call it.
the problem mixing way work objects , way work arrays.
for 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+')'; } ); (var item in func) { wscript.echo('calling func['+item+']='+ func[item](1)); };
for 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+')'; }; (var item in func) { wscript.echo('calling func['+item+']='+ func[item](1)); };
as can see, similar, if work arrays, should add elements array, not properties, for in
iterate on elements in array. in case of object approach, add properties object , for in
iterates on properties of object.
very similar, not same.
Comments
Post a Comment