A variable in global scope
var a1 = 'contents of global variable a1';
can be references (with some limitations) as
window['a1']; // or
window.a1; // or even
window['a'+'1'];
Thus the variable name a1 can be constructed on the fly, dynamically.
Whether
that is useful ... at least it is fun. One could play with selfmodifying
code.
If the variable is local inside a function
var f = function () {
var a1 = 'contents of local variable a1 inside f';
this.b1 = 'contents of this.b1 inside f';
// how to refer to variable a1 as a property of something? x['a1'] ?
what is x?
return a1;
}
I am a bit (!) confused: functions are objects, but
var a1 inside f is not a property or is it?
Variable this.b1 is actually global, at least the
variable b1 below was overwritten in a test.
var b1 = 'global variable b1 contents';
So, the question is:
// how to refer to variable a1 as a property of something, if
var a1 is inside the function f? x['a1'] ? what is x? Or is it
impossible?
var a1 = 'contents of global variable a1';
can be references (with some limitations) as
window['a1']; // or
window.a1; // or even
window['a'+'1'];
Thus the variable name a1 can be constructed on the fly, dynamically.
Whether
that is useful ... at least it is fun. One could play with selfmodifying
code.
If the variable is local inside a function
var f = function () {
var a1 = 'contents of local variable a1 inside f';
this.b1 = 'contents of this.b1 inside f';
// how to refer to variable a1 as a property of something? x['a1'] ?
what is x?
return a1;
}
I am a bit (!) confused: functions are objects, but
var a1 inside f is not a property or is it?
Variable this.b1 is actually global, at least the
variable b1 below was overwritten in a test.
var b1 = 'global variable b1 contents';
So, the question is:
// how to refer to variable a1 as a property of something, if
var a1 is inside the function f? x['a1'] ? what is x? Or is it
impossible?
Comment