因爲實際上這裏沒有作用域。所有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'的變量相同,這是一件壞事,因爲這會使變量請參閱全局範圍,而不是函數本地範圍。 –