所以當我在任何函數的作用域之外聲明一個變量時,它就成爲窗口對象的一個屬性。但是當我在函數的範圍內聲明一個變量時呢?例如,在下面的代碼中,我可以將x視爲窗口的屬性,即window.x,但y怎麼辦?它是否曾經是一個物體的屬性?當我在一個函數中聲明一個變量時,哪個對象是它的一個屬性?
var x = "asdf1";
function test() {
var y = "asdf2";
}
test();
所以當我在任何函數的作用域之外聲明一個變量時,它就成爲窗口對象的一個屬性。但是當我在函數的範圍內聲明一個變量時呢?例如,在下面的代碼中,我可以將x視爲窗口的屬性,即window.x,但y怎麼辦?它是否曾經是一個物體的屬性?當我在一個函數中聲明一個變量時,哪個對象是它的一個屬性?
var x = "asdf1";
function test() {
var y = "asdf2";
}
test();
它變成與函數調用關聯的Variable對象的屬性。實際上,這與函數調用的Activation對象是一樣的。
雖然我不相信Variable對象可以被運行JavaScript代碼訪問;它更像是一個實現細節,而不是你可以利用的東西。
Access all local variables這裏是一個關於SO的相關問題。
參見下面的例子(我有其他問題回答複印件)很漂亮:
// 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);
如果您複製了他人的答案,您至少應該提供一個參考。無論如何,我不認爲你真的回答了這個問題。 – user113716 2011-03-01 17:47:24
@帕特里克:我有我的電腦複製這個編!這是一個非常好的程序,用於在Java腳本中理解對象概念 – 2011-03-01 17:52:57
我已經去鏈接。 (搜索谷歌,並找到它):) http://stackoverflow.com/questions/500431/javascript-variable-scope – 2011-03-01 17:54:54
爲了宣佈一個JS變量,你需要可以使用新的對象()一個對象的屬性;方法或{}語法。
var variableName = new Object();
var variableName = {myFirstProperty:1,myNextProperty:'hi',etc};
然後你可以指定子對象或屬性表示變量對象
variableName.aPropertyNameIMadeUp = 'hello';
variableName.aChildObjectNameIMadeUp = new Object();
這樣的新變量對象與方法有關,如果它是在方法調用中。
乾杯
+1雖然我覺得OP想知道,如果它是可訪問的*爲*一個對象的屬性,所以也許值得注意的是,可變對象是不能直接訪問。 – user113716 2011-03-01 17:43:46
我相信它可以通過SpiderMonkey中的Function.__ scope__直接訪問(但不包括)Firefox 4.無法在任何其他UA中訪問它,並且一旦您開始在SpiderMonkey中使用該對象時,就無法保證。 – gsnedders 2011-03-02 10:47:47