this在vue和小程序中的使用详解

2020-06-14 06:15:19易采站长站整理

如果你的项目支持ES6标准,那么

箭头函数是你最佳选择


getData() {
axios.get('https://easy-mock.com/mock/5b0525349ae34e7a89352191/example/promise1')
.then(() => {
console.log(this.message);
})
}

我们在之前的文章中总结过一个结论

this的指向是在函数执行的时候定义的,而不是在函数创建时定义的,this指向的是最后调用它的对象

我们接下来本篇文章的另一个知识点

箭头函数中的this

看一个栗子


var heroName = '黄蓉';
var heroObj = {
heroName: '郭靖',
callName: function () {
console.log(this.heroName)//=>郭靖
}
}
heroObj.callName();

this指向最后调用它的对象,所以输出=>郭靖

再看下箭头函数的栗子


var heroName = '黄蓉';
var heroObj = {
heroName: '郭靖',
callName: () => {
console.log(this.heroName)//=>黄蓉
}
}
heroObj.callName();

对这个输出结果感到意外吗?

不管懵没懵,我们再看一个栗子


var heroName = '黄蓉';
function getHeroName() {
this.heroName = '郭靖'
const foo = () => {
console.log(this.heroName)//=>郭靖
}
foo();
}
getHeroName();

放在一起做一下比较:

普通函数:this的指向是在函数 执行 的时候绑定的,而不是在函数 创建 时绑定的

箭头函数:this的指向是在函数 创建 的时候绑定的,而不是在函数 执行 时绑定的。

不管在什么情况下,箭头函数的this跟外层function的this一致,外层function的this指向谁,箭头函数的this就指向谁,如果外层不是function则指向window。

ES6中定义的时候绑定的this是继承的父执行上下文里面的this

小程序中的this

如果项目中的小程序也支持ES6标准,无疑,使用箭头函数是一个不错的选择


//省略。。。
getLocation() {
wx.chooseLocation({
success: res => {
if (res.address && res.name) {
this.setData({
shopAddress: `${res.address}(${res.name})`
})
} else if (res.address) {
this.setData({
shopAddress: `${res.address}`
})
}
}
})
}

很多场景就不需要缓存中转this


var that = this//使用箭头函数替代此方案

合理的使用this会使我们事半功倍