zoukankan      html  css  js  c++  java
  • ES6笔记之 arrow function

    arrow function 箭头函数,应该是ES6语法中应用最多的地方
    长期以来 JavaScript语言的this对象一直是一个令人头痛的问题,在对象方法中使用this,必须小心

    class Animal {
        constructor(){
            this.type = 'animal'
        }
        says(say){
            setTimeout(function(){
                console.log(this.type + ' says ' + say)
            }, 1000)
        }
    }

    如setTimeout(function(){},1000) 里的function,这里想打印出this.type,却会报错,原因是因为这里的this指向函数的使用者window全局对象

    传统的解决办法有两种

    第一种是将this传给self,再用self来指代this

       says(say){
           var self = this;
           setTimeout(function(){
               console.log(self.type + ' says ' + say)
           }, 1000)
      }

    第二种方法是用bind(this),即

       says(say){
           setTimeout(function(){
               console.log(this.type + ' says ' + say)
           }.bind(this), 1000)
      }
    但现在我们有了箭头函数,就不需要这么麻烦了:
     
    class Animal {
        constructor(){
            this.type = 'animal'
        }
        says(say){
            setTimeout( () => {
                console.log(this.type + ' says ' + say)
            }, 1000)
        }
    }
     var animal = new Animal()
     animal.says('hi')  //animal says hi

    我们使用箭头函数时,函数体内的this对象,就是定义时所在的对象,而不是使用时所在的对象。并不是因为箭头函数内部有绑定this的机制,实际原因是箭头函数根本没有自己的this,它的this是继承外面的,因此内部的this就是外层代码块的this。

  • 相关阅读:
    Oracle创建database link(dblink)和同义词(synonym)
    spring boot 集成 quartz 定时任务
    tomcat 启动Spring boot 项目
    UUID+随机数
    js常用字符串处理方法
    Win10安装mysql-8.0.11-winx64详细步骤
    ORA-02049: 超时: 分布式事务处理等待锁
    spring boot 发邮件
    bootstrap table 列求和
    spring boot 延长 Session 时间
  • 原文地址:https://www.cnblogs.com/studyhtml5/p/7150683.html
Copyright © 2011-2022 走看看