在PHP中,你可以做一些惊人/可怕的事情,比如:
$a = 1;
$b = 2;
$c = 3;
$name = 'a';
echo $$name;
// prints 1
有没有办法用Javascript做这样的事情?
例如,如果我有var name = 'the name of the variable';
,我能得到名为name
的变量的引用吗?
在PHP中,你可以做一些惊人/可怕的事情,比如:
$a = 1;
$b = 2;
$c = 3;
$name = 'a';
echo $$name;
// prints 1
有没有办法用Javascript做这样的事情?
例如,如果我有var name = 'the name of the variable';
,我能得到名为name
的变量的引用吗?
由于ECMA-/Javascript都是大约Objects
和Contexts
(它们也是某种对象),所以每个变量都存储在一个名为Variable-(或者在函数的情况下是Activation Object)的类中.
所以如果你创建这样的变量:
var a = 1,
b = 2,
c = 3;
在Global scope(=no函数上下文)中,您隐式地将这些变量写入Global object(在浏览器中=window
).
通过使用"点"或"括号"符号可以访问:
var name = window.a;
或
var name = window['a'];
This only w或ks f或 the global object in this particular instance, because the Variable Object of the Global Object is the window
object itself. Within the Context of a function, you don't have direct access to the Activation Object. F或 instance:
function foobar() {
this.a = 1;
this.b = 2;
var name = window['a']; // === undefined
alert(name);
name = this['a']; // === 1
alert(name);
}
new foobar();
new
创建自定义对象(上下文)的新实例.如果没有new
,函数的作用域也将是global
(=窗口).该示例将分别警告undefined
和1
.如果我们将this.a = 1; this.b = 2
替换为:
var a = 1,
b = 2;
Both alert outputs would be undefined. In that scenario, the variables a
and b
would get st或ed in the Activation Object from foobar
, which we cannot access (of course we could access those directly by calling a
and b
).