鍍金池/ 問答/Java  網絡安全  HTML/ ES6中箭頭函數(shù)作為對象屬性,this的指向問題

ES6中箭頭函數(shù)作為對象屬性,this的指向問題

看了阮大神ES6入門一書的時候,介紹箭頭函數(shù)this

this指向的固定化,并不是因為箭頭函數(shù)內部有綁定this的機制,實際原因是箭頭函數(shù)根本沒有自己的this,導致內部的this就是外層代碼塊的this。

網上也有云

箭頭函數(shù)的this綁定看的是this所在的函數(shù)定義在哪個對象下,綁定到哪個對象則this就指向哪個對象
const Person = {
        'sayHello': () => {console.log(this)}
            };
      Person.sayHello();

這里的this為什么指向window?為什么不是外部代碼塊的Person對象的this.

回答
編輯回答
蟲児飛

你的代碼等效為:

const func = () => {
  console.log(this);
};

const Person = {
  hello: func,
};

Person.hello();

那么自然就是 window 咯,聲明函數(shù)的地方是 window 嘛。

2018年7月9日 09:10
編輯回答
臭榴蓮

使用對象字面量的時候,不要在其定義的方法里使用箭頭函數(shù),這屬于箭頭函數(shù)的禁忌。另外,可以看下下面的代碼執(zhí)行:

var obj = {
  i: 10,
  b: () => console.log(this.i, this),
  c: function() {
    console.log( this.i, this)
  },
  d() {
    console.log( this.i, this)  
  }
}
obj.b(); 
obj.c();
obj.d(); 

2018年2月8日 07:01
編輯回答
浪蕩不羈

更新

const person = {
    sayHello: () => console.log(this)
}

const Person = function() {
    this.sayHello = () => console.log(this)
}

const pI = new person()
// 報錯: person is not a constructor

const PI = new Person()
PI.sayHello() 

clipboard.png


你看看 Person:

clipboard.png

再看看 window:

clipboard.png

你不覺得這兩個東西有哪里不太一樣嗎?

const Person = {
    // ...
}

這種形式,你只是定義了一個數(shù)據(jù)而不是對象,對象是要求有 constructor 構造器定義的。

2018年2月25日 07:47