es6 箭头函数

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

demo:this

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命令,不然会抛出一个错误spa

不能使用arguments对象code

不能使用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对象,在严格模式下是undefinedblog

使用箭头函数定义作用域

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');
相关文章
相关标签/搜索