zoukankan      html  css  js  c++  java
  • 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');
  • 相关阅读:
    jenkins+maven+svn的自动化部署
    python+selenium遇到鼠标悬停不成功可以使用js进行操作
    robot framework环境搭建
    selenium+python定位元素方法
    selenium+python元素操作
    selenium+python等待时间
    selenium+python浏览器窗口的切换
    jmeter学习(七)连接mysql 数据库
    jmeter学习(六)集合点和关联
    jmeter学习(五)参数化
  • 原文地址:https://www.cnblogs.com/xiaofenguo/p/10653913.html
Copyright © 2011-2022 走看看