• 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');
  • 相关阅读:
    pytorch——nn.Module
    jQuery性能优化的28个建议
    javascript string 转 date
    javascript 追加date format属性。
    javascript翻页小控件paginator
    getTime()的00:00:00问题。
    禁止输入表情的方法
    解决带有导航的情况下 关于present自动返回的问题
    设置透明色
    class can not be find with platformType:1 step 1
  • 原文地址:https://www.cnblogs.com/xiaofenguo/p/10653913.html
Copyright © 2020-2023  润新知