当前位置: 移动技术网 > IT编程>开发语言>JavaScript > 微信小程序中为什么使用var that=this

微信小程序中为什么使用var that=this

2019年09月07日  | 移动技术网IT编程  | 我要评论

前言:

  在小程序或者js开发中,经常需要使用var that = this;开始我以为是无用功,(原谅我的无知),后来从面向对象的角度一想就明白了,下面简单解释一下我自己的理解,欢迎指正批评。

代码示例:

page({
 data: {
  test:10
 },
 testfun1: function () {
  console.log(this.data.test) // 10
  function testfun2(){
   console.log(this.data.test) //undefined
  }
  testfun2()
 },
})

第一个this.data.test打印结果为10,原因是因为this的指向是包含自定义函数testfun1()的page对象。

第二个打印语句实际上会报错,原因是在函数testfun2()中,this指向已经发生改变,也不存在data属性,会error:cannot read property 'data' of undefined;

  解决办法 为复制一份this的指向到变量中,这样在函数执行过程中虽然this改变了,但是that还是指向之前的对象。

  testfun1: function () {
  var that = this
  console.log(this.data.test) // 10
  function testfun2() {
   console.log(that.data.test) // 10
  }
  testfun2()
 },
 onload:function(){
  this.testfun1();
 }

  编译之后没有报错,正常打印出结果;

  再来一项更明白的例子:

 onload: function() {
  var testvar = {
   name: "zxin",
   testfun3: function() {
    console.log(this.name);
   }
  }
  testvar.testfun3();
 }

 编译后输出结果:zxin。this.name指的是testvar对象,testfun3()也属于testvar对象。

 总结:

大家知道this是指当前对象,只是一个指针,真正的对象存放在堆内存中,this的指向在程序执行过程中会变化,因此如果需要在函数中使用全局数据需要合适地将this复制到变量中。

以上所述是小编给大家介绍的微信小程序中为什么使用var that=this,希望对大家有所帮助

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网