区别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 
原文地址:https://www.cnblogs.com/luxiaoyao/p/8541625.html