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。

  • 相关阅读:
    lua table
    lua basic
    lua5.4 coroutine的通俗理解
    HarmonyOS实战—实现双击事件
    HarmonyOS实战—单击事件的四种写法
    HarmonyOS实战—实现单击事件流程
    苹果CMS对接公众号教程
    Spring快速入门
    YYCMS搭建影视网站教程
    分享几个开源Java写的博客系统
  • 原文地址:https://www.cnblogs.com/studyhtml5/p/7150683.html
Copyright © 2011-2022 走看看