zoukankan      html  css  js  c++  java
  • ES6箭头函数

    ES6 中,箭头函数就是函数的一种简写形式,使用括号包裹参数,跟随一个 =>,紧接着是函数体:

    var getPrice = function() {
      return 4.55;
    };
    
    // Implementation with Arrow Function
    var getPrice = () => 4.55;

    需要注意的是,上面栗子中的 getPrice 箭头函数采用了简洁函数体,它不需要 reture 语句,下面这个栗子使用的是正常函数体:

    var materials = [
      'Hydrogen',
      'Helium',
      'Lithium',
      'Beryllium'
    ];
    
    materials.map(function(material) { 
      return material.length; 
    }); // [8, 6, 7, 9]
    
    materials.map((material) => {
      return material.length;
    }); // [8, 6, 7, 9]
    
    materials.map(material => material.length); // [8, 6, 7, 9]

    当然,箭头函数不仅仅是让代码变得简洁,函数中 this 总是绑定总是指向对象自身。具体可以看看下面几个栗子:

    我们经常需要使用一个变量来保存 this,然后在 growUp 函数中引用:

    function Person() {
      var self = this;
      self.age = 0;
    
      setInterval(function growUp() {
        self.age++;
      }, 1000);
    }
    var person = new Person();

    An arrow function does not have its own this; the this value of the enclosing execution context is used. Thus, in the following code, the this within the function that is passed to setInterval has the same value as this in the enclosing function:

    function Person(){
      this.age = 0;
    
      setInterval(() => {
        // |this| 指向 person 对象
        this.age++;
      }, 1000);
    }
    
    var person = new Person();
  • 相关阅读:
    HDU 2066 一个人的旅行 最短路问题
    HDU 2112 HDU Today 最短路
    HDU 2521 反素数 模拟题
    mac 安装 office
    selenium用法 (python)
    selenium遇到不可编辑input和隐藏input如何赋值
    mac 下bash命令
    ssh 自动登录
    linux常用命令
    json字符串调整
  • 原文地址:https://www.cnblogs.com/wujiaqi/p/7727297.html
Copyright © 2011-2022 走看看