這篇文章將為大家詳細(xì)講解有關(guān)微信小程序中報錯this.setData怎么辦,小編覺得挺實用的,因此分享給大家做個參考,希望大家閱讀完這篇文章后可以有所收獲。
先說原因:
function聲明的函數(shù)和箭頭函數(shù)的作用域不同,這是一個不小心坑的地方。可參考箭頭函數(shù)說明:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions
所以對于這個結(jié)果,還是換回es5的function函數(shù)去寫最好了。
箭頭函數(shù)和function的區(qū)別:
箭頭函數(shù)體內(nèi)的this對象,就是定義時所在的對象,而不是使用時所在的對象
箭頭函數(shù)不可以當(dāng)作構(gòu)造函數(shù),也就是說,不可以使用new命令,否則會拋出一個錯誤
箭頭函數(shù)不可以使用arguments對象,該對象在函數(shù)體內(nèi)不存在。如果要用,可以用Rest參數(shù)代替,不可以使用yield命令,因此箭頭函數(shù)不能用作Generator函數(shù)。
這么寫會報錯
thirdScriptError this.setData is not a function;at pages/index/index onLoad function;at api getSystemInfo success callback function TypeError: this.setData is not a function
onLoad: function () { wx.getSystemInfo({ success: function (res) { this.setData({ lang: res.language }) console.log(res.language) } })
這么改一下就不報錯了。
onLoad: function() { wx.getSystemInfo({ success: (res) = >{ this.setData({箭頭函數(shù)的this始終指向函數(shù)定義時的this lang: res.language }) console.log(res.language) } })
或者這樣:
onLoad: function () { var that=this; wx.getSystemInfo({ success: function (res) { that.setData({ lang: res.language }) console.log(res.language) } })
可以用如下示例說明:
'use strict'; var obj = { i: 10, b: () => console.log(this.i, this), c: function() { console.log(this.i, this); } } obj.b(); // prints undefined, Window {...} (or the global object) obj.c(); // prints 10, Object {...}
關(guān)于“微信小程序中報錯this.setData怎么辦”這篇文章就分享到這里了,希望以上內(nèi)容可以對大家有一定的幫助,使各位可以學(xué)到更多知識,如果覺得文章不錯,請把它分享出去讓更多的人看到。
另外有需要云服務(wù)器可以了解下創(chuàng)新互聯(lián)scvps.cn,海內(nèi)外云服務(wù)器15元起步,三天無理由+7*72小時售后在線,公司持有idc許可證,提供“云服務(wù)器、裸金屬服務(wù)器、高防服務(wù)器、香港服務(wù)器、美國服務(wù)器、虛擬主機(jī)、免備案服務(wù)器”等云主機(jī)租用服務(wù)以及企業(yè)上云的綜合解決方案,具有“安全穩(wěn)定、簡單易用、服務(wù)可用性高、性價比高”等特點與優(yōu)勢,專為企業(yè)上云打造定制,能夠滿足用戶豐富、多元化的應(yīng)用場景需求。