JS 虚拟函数与普通函数的this指向 (uni-app 上传图片回显一直不成功)
写点业务代码,没想道在这上面翻了车:
事情的原委是有一个
success
回调函数,参数为res
,我在函数中使用了this
来访问一些数据,但是总是报错,大致意思是说这个数据在this
中未定义。
修改前的源代码如下:
success (res) {
uni.showToast({
title: '上传成功',
mask: true,
})
this.imgArr = res.tempFilePaths
console.log(this.imgArr)
}
找了一大圈资料,99%都没p用,直到我找到了这篇文章👇:
关于UNI-APP中请求获取到数据,但无法渲染,微信开发工具APPDATA中没有数据的问题,THIS指向问题
顿时恍然大悟,于是把代码修改成了:
success: res => {
uni.showToast({
title: '上传成功',
mask: true,
})
this.imgArr = res.tempFilePaths
console.log(this.imgArr)
}
解决完毕,下面来讲讲 this
指向问题:
这里直接给出别人的🔗总结:
- 箭头函数不会创建自己的 this,始终指向箭头函数声明时所在作用域下的 this 值,也就是从箭头函数所在作用域的父层继承this。
- 使用function定义的普通函数,this的指向随着调用环境的变化而变化,即:**this指向调用该函数的对象,如果没有直接指定就是window,**具体有以下几种情况:
function Person(color) {
console.log(this)
this.color = color;
this.getColor = function () {
console.log(this)
return this.color;
};
this.setColor = function (color) {
console.log(this)
this.color = color;
};
}
Person("red"); //this指向 window
var p = new Person("yello"); //this指向 p
p.getColor(); //this指向 p
var obj = {};
p.setColor.call(obj, "black"); //this指向 obj
var test = p.setColor;
test(); //this指向 window
function fun1() {
function fun2() {
console.log(this);
}
fun2(); //this指向 window
}
fun1();