給定如下:
。function MyClass() {
this.name = "Agnus"。
return function() {
console.log(this.name)
}
}
const user = new MyClass() //this = "MyClass"/span>
const r = MyClass() //this = "window"
console.log(name) /Agnus, this = "window"
r() /Agnus, this = "window"
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" class="snippet-box-edit snippet-box-result" frameborder="0"></iframe>
我的期望是,在呼叫r()時,我將得到一個錯誤,因為 "this "的值對于它的情況來說是一個視窗,但它卻回傳給我 "Agnus"。在檢查時,我發現物件構造器MyClass的屬性可以從全域獲得。
我很難理解這種行為,所以如果有人能給我解釋一下,那就太好了。
謝謝你的幫助。
uj5u.com熱心網友回復:
當你使用new時,你將this設定為一個新的空物件,其內部原型是建構式的.prototype。這就是:
new MyClass()
function MyClass() {
//`this`現在相當于Object.create(MyClass.prototype)。
但是如果你明確地從建構式中回傳一個物件,this基本上將被丟棄,而回傳的物件將被替代使用。這里,回傳的物件是函式,而
this.name = "Agnus"
line 賦值給一個物件,這個物件再也不會被參考了。
相反,當你不使用new,并且你呼叫的函式不是一個物件的屬性(或系結,或一個箭頭函式),this將是全域物件(在sloppy模式),或undefined(在嚴格模式)。在馬虎模式下,
function MyClass ( ) {
this.name = "Agnus"
does
window.name ="Agnus"。
然后當你后來用r()呼叫回傳的函式時,由于它不是一個物件的屬性,它的this是全域物件--其name是Angus。
為了減少混淆,我建議
- 避免從建構式中明確回傳物件 。
- 在呼叫建構式時總是使用
new。
你不必必須這樣做,但是如果你這樣做,你就會減少對自己(以及代碼的其他讀者)的困惑。
嚴格模式也是一個好主意。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/321028.html
標籤:
上一篇:小牛馬的編程

