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;
});
}
}
两者的作用一致
网友评论