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。

  • 相关阅读:
    从零到一搭建测试框架
    一文说懂join和setDaemon
    工具代码-timeout
    算法-广度优先遍历-实战-多轮状态
    调用百度AI新闻摘要API
    基于numpy用滑窗方差的办法确定曲线拐点
    python实现离线语音识别
    图床
    传智课堂的授课方案
    C#后台程序与HTML页面中JS方法互调
  • 原文地址:https://www.cnblogs.com/studyhtml5/p/7150683.html
Copyright © 2011-2022 走看看