据我所知,不带“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