![](/img/trans.png)
[英]JavaScript normal function vs arrow function - how to set new scope
[英]Javascript arrow function lexical scope: object literal vs “new” operator
我試圖了解箭頭函數在 JS 中是如何工作的。 讓我困惑的一件事是:
let obj1 = { // MDN states that object literal does not create a new scope but I didn't find
// any detailed explanation why
name: "benny",
getName: () => {
console.log(this.name);
},
};
obj1.getName(); // prints "undefined"
class myObj {
constructor() {
this.name = "benny";
this.getName = () => {
console.log(this.name);
};
}
}
let obj2 = new myObj();
obj2.getName(); //prints "benny"
有人可以解釋為什么 object 文字不會創建新的 scope,而調用“新”會嗎? (我一直認為 object 字面量和“new”運算符是相等的;我在 MDN 中沒有找到正確的解釋。)我找到了關於 new 運算符如何工作的解釋。 但我不清楚為什么 object 文字的工作方式不同。
提前致謝!
new
運算符不會創建新的 scope。
函數創建一個新的 scope。
constructor
function 是與全局外部任意函數空間不同的 function。
因此,每當您在任何地方使用箭頭 function 時,它都不會擁有自己的this
,因為它會從其父函數中引用this
(簡單起見)。
因此,在第一種情況下,它指this
是 window ,因此是undefined
。
在第二種情況下,指的是構造函數的“this”,因此是“benny”。
class myObj { constructor() { this.name = "benny"; } getName() { console.log(this.name); } getName2 = () => { console.log(this.name); } } let obj2 = new myObj(); obj2.getName(); obj2.getName2();
我想提出這個例子是因為我認為它很有趣——這並不是直接回答你的問題,而只是一些額外的信息。
人們在談論如何在構造函數中定義它使this
屬性引用 object 本身——因為this
就是在構造函數中的意思,所以我想看看如果你以我的方式定義箭頭 function 會發生什么上面用getName2
完成——它不在構造函數中,但它仍然將this
定義為 object 本身。 所以為什么?
好吧,事實證明,當您以這種方式定義箭頭函數時,它實際上最終是在構造函數中定義的。 我認為像這樣的箭頭函數正在進行某種code hoisting
。 您實際上可以通過嘗試更改原型上的 function 來驗證它:
myObj.prototype.getName = () => {console.log('hello world')}
myObj.prototype.getName2 = () => {console.log('hello world')}
obj2.getName(); // this prints 'hello world'
obj2.getName2(); // this does not
您不能通過原型更改 getName2 的getName2
,因為 function 實際上是在幕后的構造函數中定義的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.