亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

微信小程序錯(cuò)誤this.setData報(bào)錯(cuò)及解決過(guò)程

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

先說(shuō)原因:

function聲明的函數(shù)和箭頭函數(shù)的作用域不同,這是一個(gè)不小心坑的地方??蓞⒖技^函數(shù)說(shuō)明:

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

所以對(duì)于這個(gè)結(jié)果,還是換回es5的function函數(shù)去寫(xiě)最好了。

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

  • 箭頭函數(shù)體內(nèi)的this對(duì)象,就是定義時(shí)所在的對(duì)象,而不是使用時(shí)所在的對(duì)象
  • 箭頭函數(shù)不可以當(dāng)作構(gòu)造函數(shù),也就是說(shuō),不可以使用new命令,否則會(huì)拋出一個(gè)錯(cuò)誤
  • 箭頭函數(shù)不可以使用arguments對(duì)象,該對(duì)象在函數(shù)體內(nèi)不存在。如果要用,可以用Rest參數(shù)代替,不可以使用yield命令,因此箭頭函數(shù)不能用作Generator函數(shù)。

這么寫(xiě)會(huì)報(bào)錯(cuò)

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)
   }
  })

這么改一下就不報(bào)錯(cuò)了。

onLoad: function() {
  wx.getSystemInfo({
    success: (res) = >{
      this.setData({箭頭函數(shù)的this始終指向函數(shù)定義時(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)
   }
  })

可以用如下示例說(shuō)明:

'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 {...}

以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。

相關(guān)文章

最新評(píng)論