【发布时间】:2011-03-01 17:36:18
【问题描述】:
所以当我在任何函数范围之外声明一个变量时,它就成为了窗口对象的一个属性。但是当我在函数范围内声明一个变量时呢?例如,在下面的代码中,我可以将 x 视为 window 的属性,即 window.x,但是 y 呢?它曾经是对象的属性吗?
var x = "asdf1";
function test() {
var y = "asdf2";
}
test();
【问题讨论】:
标签: javascript
所以当我在任何函数范围之外声明一个变量时,它就成为了窗口对象的一个属性。但是当我在函数范围内声明一个变量时呢?例如,在下面的代码中,我可以将 x 视为 window 的属性,即 window.x,但是 y 呢?它曾经是对象的属性吗?
var x = "asdf1";
function test() {
var y = "asdf2";
}
test();
【问题讨论】:
标签: javascript
它成为与函数调用关联的变量对象的属性。实际上,这与函数调用的 Activation 对象是一回事。
不过,我不相信运行 JavaScript 代码可以访问 Variable 对象;它更多的是实现细节,而不是您可以利用的东西。
Access all local variables 是关于 SO 的相关问题。
【讨论】:
为了将 JS 变量声明为对象的属性,您需要使用 new Object();方法或 {} 语法。
var variableName = new Object();
var variableName = {myFirstProperty:1,myNextProperty:'hi',etc};
然后您可以将子对象或属性分配给所述变量对象
variableName.aPropertyNameIMadeUp = 'hello';
variableName.aChildObjectNameIMadeUp = new Object();
因此,如果新变量对象在方法调用中,则它与方法相关联。
干杯
【讨论】:
看下面的例子(我有其他问答的副本)非常好:
// a globally-scoped variable
var a=1;
// global scope
function one(){
alert(a);
}
// local scope
function two(a){
alert(a);
}
// local scope again
function three(){
var a = 3;
alert(a);
}
// Intermediate: no such thing as block scope in javascript
function four(){
if(true){
var a=4;
}
alert(a); // alerts '4', not the global value of '1'
}
// Intermediate: object properties
function Five(){
this.a = 5;
}
// Advanced: closure
var six = function(){
var foo = 6;
return function(){
// javascript "closure" means I have access to foo in here,
// because it is defined in the function in which I was defined.
alert(foo);
}
}()
// Advanced: prototype-based scope resolution
function Seven(){
this.a = 7;
}
// [object].prototype.property loses to [object].property in the scope chain
Seven.prototype.a = -1; // won't get reached, because 'a' is set in the constructor above.
Seven.prototype.b = 8; // Will get reached, even though 'b' is NOT set in the constructor.
// These will print 1-8
one();
two(2);
three();
four();
alert(new Five().a);
six();
alert(new Seven().a);
alert(new Seven().b);
【讨论】: