JS 虚拟函数与普通函数的this指向 (uni-app 上传图片回显一直不成功)

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();
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值