據我所知,不帶「new」關鍵字調用的函數將其所有屬性吐出到全局上下文中。但我看到一些奇怪的行爲,這片的Javascript代碼:全局範圍內的函數
function Test3() {
var a=0;
this.inc = function() {
return ++a;
};
this.noInc = function() {
return a;
};
this.testRef = function() {
return this;
};
return {
inc: inc,
testRef: testRef,
noInc: noInc
};
}
var o = Test3(); // Put func properties on global context
var o2 = Test3(); // Put func properties on global context (replacing properties above??)
// Both "o" and "o2" maintain their own copy of "a" (closure)
alert("o: " + o.inc());
alert("o: " + o.inc());
alert("o: " + o.inc()); // Will output 3 (as expected)
alert(noInc()); // Output: 1 (This seems to not be affected by o.inc() calls - expected)
// However...
alert("o2: " + o2.inc());
alert("o2: " + o2.inc());
alert("o2: " + o2.inc());
alert("o2: " + o2.inc()); // Will output 4 (as expected)
alert(noInc()); // Will output 4 (seems to share with o2), but why?
alert(o === window); // false
alert(o.testRef() === o); // true (I thought testRef() would be on global context?)
alert(o.testRef() === window); // false (^^)
alert(o2 === window); // false
alert(o2.testRef() === o2); // true (I thought testRef() would be on global context?)
alert(o2.testRef() === window); // false (^^)
alert(testRef() === window); // true (How come this is here? Look at comments above)
當我們調用
var o = Test()
,到底發生了什麼嗎?Test()
在什麼情況下執行。由於new
關鍵字缺失,我相信,this
裏面的Test3()
會參考窗口? 「o」指的是什麼?它只是一個在全局上下文中聲明的變量嗎?如果上述屬實,那麼o和o2如何能夠維護Test3局部變量「a」的單獨副本。我知道我們在這裏已經關閉了,但是接下來怎麼回事,「o2」和「window」共享同一個變量「a」,但不是「o」當我做var o = Test3時()然後做alert(o.testRef()===窗口),它說錯誤。所以執行後:
var o = Test3(); var o2 = Test3();
似乎有從Test3()
屬性的3份。一個關於「o」,另一個關於「o2」,另一個關於全球範圍。
但是怎麼能有「o」和「o2」 - 我不是用「new」關鍵字調用Test3()
,所以這應該只涉及全局上下文?
幫你一個忙,把''use strict';'加到腳本的頂部。 – Pointy
在JSBin中工作。我認爲它默認啓用了「嚴格」。試圖嚴格使用;但JSBin正在抱怨這一行。什麼會有「嚴格」做? –
@TahaAhmad你有沒有把''嚴格使用';'或'嚴格使用'?你應該使用帶引號的那個... – dg123