博客
关于我
小程序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 Blob保存方式,oracle 存储过程操作blob
查看>>
Oracle BMW Racing sailing vessel帆船图
查看>>
ORACLE Bug 4431215 引发的血案—原因分析篇
查看>>
Oracle Business Intelligence Downloads
查看>>
Oracle cmd乱码
查看>>
Oracle Corp甲骨文公司推出Oracle NoSQL数据库2.0版
查看>>
【Docker知识】将环境变量传递到容器
查看>>
uniapp超全user-agent判断 包括微信开发工具 hbuilder mac windows 安卓ios端及本地识别
查看>>
Oracle DBA课程系列笔记(20)
查看>>
oracle dblink 创建使用 垮库转移数据
查看>>
oracle dblink结合同义词的用法 PLS-00352:无法访问另一数据库
查看>>
Oracle dbms_job.submit参数错误导致问题(ora-12011 无法执行1作业)
查看>>
oracle dg switchover,DG Switchover fails
查看>>
Oracle E-Business Suite软件 任意文件上传漏洞(CVE-2022-21587)
查看>>
Oracle EBS OPM 发放生产批
查看>>
Oracle EBS-SQL (BOM-15):检查多层BOM(含common BOM).sql
查看>>
Oracle EBS环境下查找数据源(OAF篇)
查看>>
oracle Extract 函数
查看>>
uni-app开发环境自动部署的一个误区(App running at...)
查看>>
Oracle GoldenGate Director安装和配置(无图)
查看>>