区别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