前言:
在小程序或者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復制到變量中。