因为实际上这里没有作用域。所有this
访问都是指window
对象。因此,当您在内部范围编辑this.myRefVar
时,实际上您正在编辑window
处的值。
var theName = "SO";
var myObject = function(){
this.theName = "SO2";
this.foo = function() {
this.theName = "SO3";
}
}
在这里,我定义了一些变量和函数。变量theName
,首先在root(window)
范围中声明,那里面myObject
范围(目前是这样的没有范围,只是为了说明,然后里面foo
范围。)
console.log(theName); // SO
console.log(this.theName); // SO
console.log(window.theName); // SO
console.log(myObject.theName); // undefined
console.log(myObject.foo); // undefined
console.log(this.foo); // undefined
console.log(window.foo); // undefined
在这里,我试图通过不同的方式访问theName
变量。如果实际上在这里进行搜索,则第4个函数应该在函数调用后工作。其他人只代表相同的想法,但方式不同。
myObject();
console.log(theName); // SO2
console.log(this.theName); // SO2
console.log(window.theName); // SO2
console.log(myObject.theName); // undefined
console.log(myObject.foo); // undefined
console.log(this.foo); // function myObject/this.foo()
console.log(window.foo); // function myObject/this.foo()
函数调用后,我仍然无法访问myObject.theName
为我所希望的。那是因为,这样调用myObject.theName
实际上并没有访问myObject
范围,而不是我试图访问theName
属性的myObject
函数。而且,如果没有实际定义/实例化/创建此功能作为对象,我无法访问属性。
myObject.theName;// undefined. Accessing myObject as a function
new myObject().theName // SO2. Accessing an object derived from myObject.
这是怎么回事在你的代码实际上是不scopping而关闭。为了更好地理解:
Scopping
Closures
Similar SO question
只需在'f1'中加''use strict';'看看会发生什么。 – ftor
我想我现在明白了,在一个函数内使用'this'(而不是''constructor' now object'method')与定义一个不使用'var'的变量相同,这是一件坏事,因为这会使变量请参阅全局范围,而不是函数本地范围。 –