這篇文章將為大家詳細講解有關微信小程序中報錯this.setData怎么辦,小編覺得挺實用的,因此分享給大家做個參考,希望大家閱讀完這篇文章后可以有所收獲。
先說原因:
function聲明的函數和箭頭函數的作用域不同,這是一個不小心坑的地方??蓞⒖技^函數說明:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions
所以對于這個結果,還是換回es5的function函數去寫最好了。
箭頭函數和function的區別:
箭頭函數體內的this對象,就是定義時所在的對象,而不是使用時所在的對象
箭頭函數不可以當作構造函數,也就是說,不可以使用new命令,否則會拋出一個錯誤
箭頭函數不可以使用arguments對象,該對象在函數體內不存在。如果要用,可以用Rest參數代替,不可以使用yield命令,因此箭頭函數不能用作Generator函數。
這么寫會報錯
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({箭頭函數的this始終指向函數定義時的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 {...}
關于“微信小程序中報錯this.setData怎么辦”這篇文章就分享到這里了,希望以上內容可以對大家有一定的幫助,使各位可以學到更多知識,如果覺得文章不錯,請把它分享出去讓更多的人看到。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。