在 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 word
closure’’ 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
解决方法同上,不再赘述。
写在最后
语法真的很重要。很多难题还是要依靠基础语法。
公众号
更多内容,欢迎关注我的微信公众号: 半夏之夜的无情剑客。