欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

微信小程序錯誤this.setData報錯及解決過程

 更新時間:2019年09月18日 16:57:08   作者:岌岌可危  
這篇文章主要介紹了微信小程序錯誤this.setData報錯及解決過程,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下

先說原因:

function聲明的函數(shù)和箭頭函數(shù)的作用域不同,這是一個不小心坑的地方。可參考箭頭函數(shù)說明:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions

所以對于這個結果,還是換回es5的function函數(shù)去寫最好了。

箭頭函數(shù)和function的區(qū)別:

  • 箭頭函數(shù)體內(nèi)的this對象,就是定義時所在的對象,而不是使用時所在的對象
  • 箭頭函數(shù)不可以當作構造函數(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 {...}

以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。

相關文章

最新評論