區別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 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM