回调函数中的this

在这里插入图片描述

JavaScript常用函数(持续更新中) 中对JavaScript的常用函数进行了介绍。本文介绍一下怎样在回调函数中使用this

JavaScript的所见即所得的便利性是很多其他语言无法比拟的,这也是笔者比较喜欢JavaScript的原因。

起因

在写鸿蒙代码的时候,有下面一段代码。

export default {
    data: {
        TextArea: "测试开始"
    },
 
    testSleep() {
        console.log('TextArea =' + this.TextArea);
        //console.log(JSON.stringify(this.$refs.textarea));
        setTimeout(function () {
            promise.then(async (rdbStore) => {
                rdbRromise.then(async (ret) => {
                    this.TextArea = this.TextArea + "\n" + "插入一条数据成功!坐标为:" + "{" + X + "," + Y + "}"
                    console.log("Burning002" + this.TextArea);
                })
            }).catch((err) => {
                this.TextArea = this.TextArea + "\n" + "插入一条数据失败,请稍后重试!"
            });
            console.log('outside success');
        }, 0);
    }
}

其中TextArea和如下的元素绑定,鸿蒙采用了类似vue的双向绑定功能。其功能主要是讲文本展示到页面中。testSleep函数功能就是定时显示文本内容

<div class="Text" >
   <textarea class="TextArea" ref="textarea">{{TextArea}}</textarea>
</div>

遗憾的是,文本内容显示不出来。根本原因是回调函数中的this和testSleep函数中的this是不一样的

解决办法

将this赋值给一个临时变量,利用js的闭包机制和引用赋值来将this传递到回调函数中去。具体如下。

testSleep() {
    console.log('TextArea =' + textArea);
    //重点在这里
    var tmpObject = this;
    setTimeout(function () {
        promise.then(async (rdbStore) => {
            rdbRromise.then(async (ret) => {
                tmpObject.TextArea = tmpObject.TextArea + "\n" + "插入一条数据成功!坐标为:" + "{" + X + "," + Y + "}"
                console.log("Burning002" + tmpObject.TextArea);
            })
        }).catch((err) => {
            tmpObject.TextArea = tmpObject.TextArea + "\n" + "插入一条数据失败,请稍后重试!"
        });
    }, 0);
}

理论部分

有兴趣的可以看看下面的内容。主要是修改涉及到的知识点。

闭包

当函数可以记住并访问所在的词法作用域,即使函数是在当前词法作用域之外执行,这时 就产生了闭包。与离散数学中的闭包没啥关系。

The use of the word closure here comes from abstract algebra, where a set of elements is said to be closed under an operation if applying the operation to elements in the set produces an element that is again an element of the set. The Lisp community also (unfortunately) uses the wordclosure’’ to describe a totally unrelated concept: A closure is an implementation technique for representing procedures with free variables.

JavaScript中的数据类型

JavaScript 定义了 6 种基本数据类型,如表所示。

  • undefined
  • null
  • string
  • number
  • boolean
  • object
console.log(typeof 1);  //返回字符串"number"
console.log(typeof "1");  //返回字符串"string"
console.log(typeof true);  //返回字符串"boolean"
console.log(typeof {});  //返回字符串"object"
console.log(typeof []);  //返回字符串"object"
console.log(typeof hi);  //返回字符串"function"
console.log(typeof null);  //返回字符串"object"
console.log(typeof undefined) ;  //返回字符串"undefined"
console.log(typeof this); //返回object

使用typeof获取数据类型,object是引用类型
在这里插入图片描述
还可以使用instanceof 等判断数据类型,具体可参考: Frida API进阶-网络

this究竟是什么

通过前面的分析,可知道,下面的回调函数中的this.a是undefined。关于JavaScript中的new操作符可参考 JavaScript常用函数(持续更新中)

function hi(a) {
	this.a = a;
	setTimeout(function () {
		console.log("Burning");
		console.log(this.a);
	}, 5000);
}
var  ob = new hi(2);
console.log(ob.a);

可以分别看一下这里的this都是什么。通过输出可知第一个this是new出来的新对象,而setTimeout中的this是Window
在这里插入图片描述解决方法同上,不再赘述。

写在最后

语法真的很重要。很多难题还是要依靠基础语法。

公众号

更多内容,欢迎关注我的微信公众号: 半夏之夜的无情剑客。
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

helloworddm

你的鼓励是我创作最大的动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值