javascript - Checking if function exist in same scope when supplied the function name -
i've got format
prototype method (simplified) , wanna check if char alphabetic (case insensitive), and if it's function declared in same scope. if is, want call function. if pass in x
should execute alert.
i'm gonna using method format date given format string. e.g. format('h:i:s')
check if h, i, , s function , call them.
how can achieve that?
i tried based on answer: https://stackoverflow.com/a/359910/1115367
here's code:
function time() { //initialization } time.prototype = { format: function (char) { if (char.test(/[a-z]/i) && typeof window[char] === 'function') { //undefined window[char](); } function x() { alert('works'); } } };
if pass in value returns: uncaught typeerror: undefined not function
there no way retrieve local variables (or function) name (as far know anyway).
declared named functions assigned variable of same name: function thing(){}
~ var thing = function(){}
global variables automatically attached window
can retrieve them name using window
object.
however, (fortunately) not case other variables.
for example
var global1 = 'thing'; // root level (no wrapping function) -> global (function(){ global2 = 'global'; // no 'var' keyword -> global variable (bad practice , not accepted in strict mode) var local = 'whatever'; // local variable function check(name){ if(window[name]) console.log('found: '+ name); else console.log('nope: '+name); } check('foo'); check('global1'); check('global2'); check('local'); }());
will output:
[log] nope: foo [log] found: global1 [log] found: global2 [log] nope: local
what can attach methods object.
edit
if option, can directly pass function argument (instead of string containing name).
function a(){} function tocall(f){ // stuff f } tocall(a);
Comments
Post a Comment