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

前言:

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

 

 


 

 

代码示例:

 

 1 Page({ 2  data: { 3 test:10 4  }, 5 testfun1: function () { 6 console.log(this.data.test) // 10 7 function testfun2(){ 8 console.log(this.data.test) //undefined 9  }10  testfun2()11  },12 })

 

  • 第一个this.data.test打印结果为10,原因是因为this的指向是包含自定义函数testfun1()的Page对象。
  • 第二个打印语句实际上会报错,原因是在函数testfun2()中,this指向已经发生改变,也不存在data属性,error:Cannot read property ‘data‘ of undefined;

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

 1 testfun1: function () { 2 var that = this 3 console.log(this.data.test) // 10 4 function testfun2() { 5 console.log(that.data.test) // 10 6  } 7  testfun2() 8  }, 9 onLoad:function(){10 this.testfun1();11 }

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

技术图片

  再来一项更明白的例子:

1 onLoad: function() {2 var testvar = {3 name: "zxin",4 testfun3: function() {5 console.log(this.name);6  }7  }8  testvar.testfun3();9 }

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

 总结:

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

相关文章