區別ES3ES5和ES6this的指向問題。區分普通函數和箭頭函數中this的指向問題

  • ES3 ES5this的指向問題 this指的是該函數被調用的對象
var foo = function () {
          this.a = 'a',
          this.b = 'b',
          this.c = {
            a: 'new a',
            b: function () {
              //new a 此時this指的是該函數被調用的對象
              return this.a;
            }
          }
      }
      console.log(new foo().c.b()); //new a
  • ES6的箭頭函數 箭頭函數的this指的是定義時this的指向,b在定義時,this指向的是c被定義時的函數
var foo = function () {
          this.a = 'a',
          this.b = 'b',
          this.c = {
            a: 'new a',
            b: () => {
              //a 箭頭函數的this指的是定義時this的指向,b在定義時,this指向的是c被定義時的函數,
              return this.a;
            }
          }
      }
      console.log(new foo().c.b()); //a
相關文章
相關標籤/搜索