• 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。

  • 相关阅读:
    linux 安装软件的方式
    git 基本操作
    交叉编译
    windows下 打印机打印操作类 VS2015
    VS2015 下 unicode 字符转换类
    C++ 多线程日志类的使用
    编译模板实例化
    C++中如何使用switch字符串
    linux下静态库与动态库
    jsoncpp 解码编码 中文为空 乱码问题
  • 原文地址:https://www.cnblogs.com/studyhtml5/p/7150683.html
Copyright © 2020-2023  润新知