es6 箭头函数

箭头函数中的this指向的是定义时的this

demo:

var demo=function(){

  this.a='a';

  this.b='b';

  this.c={a:'a+',b:function(){reurn this.a}}

}

var demo1=function(){

  this.a='a';

  this.b='b';

  this.c={a:'a+',b:()=> this.a}

}

console.log(new demo().c.b())//a+// 普通函数this指向调用方的this

console.log(new demo1().c.b())//a//箭头函数,this指向定义时的this

箭头函数不能作为构造函数,不能使用new命令,否则会抛出一个错误

不能使用arguments对象

不能使用yield命令

class Person{

  constructor(){

    this.name="zhangsan";
  }

  say(msg){  

    setTimeout(function(){

      console.log(this);//window
      console.log(msg+"  "+this.name);//hello  undefined
    },1000);

  }  

}

var person=new Person();

person.say('hello');

超时调用的代码都是在全局作用域中执行的,因此不管函数在哪儿,其中的this在非严格模式下指向window对象,在严格模式下是undefined

使用箭头函数定义

class Person{

  constructor(){

    this.name="zhangsan";

  }

  say(msg){  

    setTimeout(()=>{

      console.log(this);//person
      console.log(msg+"  "+this.name);//hello  zhangsan

    },1000);

  }  

}

var person=new Person();

person.say('hello');
原文地址:https://www.cnblogs.com/xiaofenguo/p/10653913.html