2011-03-01 43 views
0

所以当我在任何函数的作用域之外声明一个变量时,它就成为窗口对象的一个​​属性。但是当我在函数的范围内声明一个变量时呢?例如,在下面的代码中,我可以将x视为窗口的属性,即window.x,但y怎么办?它是否曾经是一个物体的属性?当我在一个函数中声明一个变量时,哪个对象是它的一个属性?

var x = "asdf1"; 

function test() { 
var y = "asdf2"; 
} 

test(); 

回答

3

它变成与函数调用关联的Variable对象的属性。实际上,这与函数调用的Activation对象是一样的。

虽然我不相信Variable对象可以被运行JavaScript代码访问;它更像是一个实现细节,而不是你可以利用的东西。

Access all local variables这里是一个关于SO的相关问题。

+0

+1虽然我觉得OP想知道,如果它是可访问的*为*一个对象的属性,所以也许值得注意的是,可变对象是不能直接访问。 – user113716 2011-03-01 17:43:46

+0

我相信它可以通过SpiderMonkey中的Function.__ scope__直接访问(但不包括)Firefox 4.无法在任何其他UA中访问它,并且一旦您开始在SpiderMonkey中使用该对象时,就无法保证。 – gsnedders 2011-03-02 10:47:47

-1

参见下面的例子(我有其他问题回答复印件)很漂亮:

// 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); 
+1

如果您复制了他人的答案,您至少应该提供一个参考。无论如何,我不认为你真的回答了这个问题。 – user113716 2011-03-01 17:47:24

+0

@帕特里克:我有我的电脑复制这个编!这是一个非常好的程序,用于在Java脚本中理解对象概念 – 2011-03-01 17:52:57

+0

我已经去链接。 (搜索谷歌,并找到它):) http://stackoverflow.com/questions/500431/javascript-variable-scope – 2011-03-01 17:54:54

0

为了宣布一个JS变量,你需要可以使用新的对象()一个对象的属性;方法或{}语法。

var variableName = new Object(); 
var variableName = {myFirstProperty:1,myNextProperty:'hi',etc}; 

然后你可以指定子对象或属性表示变量对象

variableName.aPropertyNameIMadeUp = 'hello'; 
variableName.aChildObjectNameIMadeUp = new Object(); 

这样的新变量对象与方法有关,如果它是在方法调用中。

干杯

相关问题