代码示例:
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对象。