站内搜索:
首页 >> 前端 >> 内容
ES6中的箭头函数实例讲解

时间:2018/4/24 14:33:48

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

var getPrice = function(){
  return 9.15;
}
// 箭头函数
var getPrice = () => 9.15;

箭头函数不仅仅是让代码变得简洁,函数中 this 总是绑定总shi 指向对象自身

function Person() {
  var self = this;
  self.age = 0;

  setInterval(function growUp() {
    self.age++;
  }, 1000);
}

使用箭头函数可以免去这个麻烦

function Person(){
  this.age = 0;
  setInterval(() => {
    // |this| 指向 person 对象
    this.age++;
  }, 1000);
}

为什么会突然发现这个东西呢,在学习Vue的时候遇到,在声明Vue时候

methods:{
    cartView: function () {
      var _this = this;
      this.$http.get("data/cartData.json").then(function (value) {
      _this.productList = value.data.result.list;
      _this.totalMoney = value.data.result.totalMoney;
    });
  }
}
methods:{
    cartView: function () {
      this.$http.get("data/cartData.json").then(res=>{
        this.productList = res.data.result.list;
        this.totalMoney = res.data.result.totalMoney;
    });
  }
}

两者的作用一致

  • 上一篇:easyUI Confirm 确认框代码实例
  • 下一篇:Content-Type中application/x-www-form-urlencoded和multipart/form-data的区别及用法详解
  • 返回顶部