博客
关于我
小程序var that=this
阅读量:440 次
发布时间:2019-03-06

本文共 735 字,大约阅读时间需要 2 分钟。

在小程序的JS函数中,通常第一句会声明var that = this,这主要是为了在后续的回调函数中保持对当前函数上下文的引用。这种做法的必要性在于,在异步操作完成后,回调函数的this可能会指向不同的对象,导致无法直接访问原函数的this。通过将当前的this保存到that变量中,可以在回调函数中使用该变量来访问原函数的this,确保能够正确地更新数据。例如,在以下代码中:

Page({  loadUsers: function () {    var that = this;    data: {      questionId: null;      title: null    }    wx.request({      url: 'http://0.0.0.0:5000/question/type=2/2',      method: 'get',      success: function(res) {        console.log(res.data);        var d = res.data['data'];        that.setData({          questionId: d['questionId'],          title: d['title']        });        console.log(that.data.questionId);      }    });  },});

如果不使用var that = this,在回调函数中直接使用this,可能会导致无法访问that.data,从而引发错误。因此,使用var that = this是保持程序正确运行的关键。

转载地址:http://bflyz.baihongyu.com/

你可能感兴趣的文章
Oracle 11g 操作ASM权限问题
查看>>
Oracle 11g 数据类型
查看>>
Oracle 11g 编译使用BBED
查看>>
oracle 11g 静默安装
查看>>
Oracle 11gR2学习之二(创建数据库及OEM管理篇)
查看>>
Oracle 11gR2构建RAC之(2)--配置共享存储
查看>>
Oracle 11g中的snapshot standby特性
查看>>
Oracle 11g关闭用户连接审计
查看>>
Oracle 11g忘记sys、system、scott密码该这样修改!
查看>>
Oracle 11g数据库安装和卸载教程
查看>>
Oracle 11g数据库成功安装创建详细步骤
查看>>
Oracle 11g超详细安装步骤
查看>>
Oracle 12c中的MGMTDB
查看>>
Oracle 12c安装报错Installation failed to access the temporary location(无法访问临时位置)...
查看>>
Oracle 9i数据库管理教程
查看>>
ORACLE Active dataguard 一个latch: row cache objects BUG
查看>>
oracle avg、count、max、min、sum、having、any、all、nvl的用法
查看>>
Oracle BEQ方式连接配置
查看>>
oracle Blob保存方式,oracle 存储过程操作blob
查看>>
Oracle BMW Racing sailing vessel帆船图
查看>>