1. 程式人生 > >關於箭頭函數中的this指向問題

關於箭頭函數中的this指向問題

生成 UC PE animal 屬性 error fun pre color

參考文章https://blog.csdn.net/zhq2005095/article/details/70666833

this的主要應用場景有:

1、在普通函數,this指向window對象。

2、函數作為對象的屬性,this指向調用函數的對象。

3、構造函數對象中,this指向函數的實例對象。

4、call和apply中,this指向第一個參數,即被擴展的作用域對象。

而ES6新增的箭頭函數的this卻有所不同,下面從以上四點對比function中的this和箭頭函數中的this。

  1 // 1、普通函數中,function和箭頭函數的this均指向window
  2 var a = 0
  3 function
foo() { 4 console.log(this) 5 console.log(this.a) 6 } 7 foo() // window 0 8 // 9 var a = 0 10 var foo = () => { 11 console.log(this) 12 console.log(this.a) 13 } 14 foo() // window 0 15 16 // 2、函數作為對象的屬性 17 var obj = { 18 name: ‘qq‘, 19 foo: function () { 20 console.log(this
) 21 console.log(this.name) 22 } 23 } 24 obj.foo() // obj qq 25 26 // 這裏箭頭函數的this指向window對象 27 var obj = { 28 name: ‘qq‘, 29 foo: () => { 30 console.log(this) 31 console.log(this.name) 32 } 33 } 34 obj.foo() // window undefined 35 36 //3、構造函數中的this 37 const Animal = function
(name, age) { 38 this.name = name 39 this.age = age 40 } 41 const animal = new Animal(‘mm‘, ‘00‘) 42 console.log(animal) // mm 00 43 44 // 箭頭函數不能作為構造函數使用!!! 45 const Animal = (name, age) => { 46 this.name = name 47 this.age = age 48 } 49 const animal = new Animal(‘mm‘, ‘00‘) 50 console.log(animal) // Uncaught TypeError: Animal is not a constructor 51 52 // 4、call和apply中的this 53 function foo() { 54 var a = 0 55 console.log(this) 56 console.log(this.a) 57 } 58 var obj = { 59 a:1 60 } 61 foo.call(obj) // obj 1 62 63 // 箭頭函數的this指向window對象 64 var a = 0 65 const func = () => { 66 console.log(this) 67 console.log(this.a) 68 } 69 var obj = { 70 a:1 71 } 72 func.call(obj) // window 0 73 74 // 函數的定義是在foo1函數生成時,函數的執行是在1000ms後,執行環境不同,回調函數中的this指向window 75 function foo1 (){ 76 // 固定this 77 var that = this; 78 setTimeout(function () { 79 console.log(this); // window 80 console.log(this.b); // undefined 81 console.log(that); // obj 82 console.log(that.b); //2 83 },1000) 84 } 85 var obj1 = { 86 b: 2 87 } 88 foo1.call(obj1); 89 90 // 箭頭函數的this指向函數定義時的作用域,foo2函數生成時箭頭函數的定義生效,this指向定義時的對象obj2 91 function foo2 () { 92 setTimeout(() => { 93 console.log(this) // obj 94 console.log(this.a) //2 95 }, 1000) 96 } 97 var obj2 = { 98 a: 2 99 } 100 foo2.call(obj2)

可以看出,箭頭函數的this指向是固定的,指向函數定義時的作用域,不能作為構造函數使用。

關於箭頭函數中的this指向問題