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

  在小程序或者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(); }

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

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

  再来一项更明白的例子:

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,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对脚本之家网站的支持!
如果你觉得本文对你有帮助,欢迎转载,烦请注明出处,谢谢!

您可能感兴趣的文章:

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:http://www.heiqu.com/1fb624f42dabb6f9a809452ccc01383b.html