zoukankan      html  css  js  c++  java
  • ES2015箭头函数与普通函数对比理解

    直接返回表达式
    var odds = evens.map(v => v + 1);
    var nums = evens.map((v, i) => v + i);
    
    var odds = evens.map(function (v) {
      return v + 1;
    });
    var nums = evens.map(function (v, i) {
      return v + i;
    });
    
    包含语句
    nums.forEach(v => {
      if (v % 5 === 0)
        fives.push(v);
    });
    
    nums.forEach(function (v) {
      if (v % 5 === 0) fives.push(v);
    });
    
    包含this

    不用修正箭头函数的this,this自动指向所在的上下文对象

    var bob = {
      _name: "Bob",
      _friends: [],
      printFriends() {
        this._friends.forEach(f =>
          console.log(this._name + " knows " + f));
      }
    };
    

    对比非箭头函数的写法会更容易理解一些:

    var bob = {
      _name: "Bob",
      _friends: [],
      printFriends: function printFriends() {
        var _this = this; // 需要修正this指向
    
        this._friends.forEach(function (f) {
          return console.log(_this._name + " knows " + f);
        });
      }
    };
    转载自:https://www.jianshu.com/p/6dee2632a717
  • 相关阅读:
    (31)对象的克隆
    (30)批处理文件.bat
    06.v-on的修饰符
    06.v-on参数问题
    06.2修饰符补充
    06.1v-on基础+-.
    03.data数据对象
    02.el挂载点
    02.5v-pre指令
    02.4v-text指令
  • 原文地址:https://www.cnblogs.com/planetwithpig/p/11685916.html
Copyright © 2011-2022 走看看