How do I reference a parent variable in JavaScript? like _parent.myvar -


i have variables set in main root of script

var name="blah"; 

i need refer within function w/o passing directly in parameters. set variables in global scope w/o using "var' initializer, , has worked function. but, still need know how similar reasons.

in flash (as2/as3) it's simple _root.myvar or _parent.myvar

in js?

sample:

var name="blah"; var sex="m"; templateme('name,sex'); // declared actual name of var not var  

then.. templateme function uses "string" passed function both variable name , corresponding value

meaning 'name' string becomes

var name=eval(name)  

here's part of function:

vars_r =  vars.split(","); r_count = vars_r.length;  if(r_count < 1 ){     return template; }  var i=0; var needles = new array(); var replacements  = new array();; for(i=0; < 2; i++){ //ti <-- use own counter coz conflicts w/ global     needles.push("{{"+ vars_r[i] + "}}");     replacements.push( eval( vars_r[i]) );  } 

etc...

hope makes more sense

global variables properties of window object. so, if need reference global variable when have name in string variable called varname, can use window[varname], this:

var foo = 'bar'; var varname = 'foo'; console.log( window[varname] ); 

which prints:

bar 

as stephen points out, there better ways tackle overall problem, approach works fine if need access global variable way.

looking @ code, think replace line:

replacements.push( eval( vars_r[i]) ); 

with:

replacements.push( window[ vars_r[i] ] ); 

although i'm not sure understand code doing. in case, window[varname] lot better eval(varname).


Comments

Popular posts from this blog

ios - iPhone/iPad different view orientations in different views , and apple approval process -

java Extracting Zip file -

C# WinForm - loading screen -