setInterval和setTImeout中的this指向问题
this 指向 setTimeout setInterval 问题
2023-09-11 14:15:07 时间
问题:在setInterval和setTimeout中传入函数时,函数中的this会指向window对象
解决方法:
1. 将当前对象的this存为一个变量,定时器内的函数利用闭包来访问这个变量。var self = this;
2.利用bind绑定
setTimeout(function(){ console.log(this.num); }.bind(this), 1000) //利用bind()将this绑定到这个函数上
3. 箭头函数
setTimeout(() => { console.log(this.num); }, 1000) //箭头函数中的this总是指向外层调用者
参考:
http://www.cnblogs.com/zsqos/p/6188835.html
相关文章
- [Web 前端] this作用域问题
- HTTP Status 500 - The absolute uri: http://java.sun.com/jsp/jstl/core cannot be resolved in either web.xml or the jar files deployed with this application
- android xml文件中出现如下提醒:This tag and its children can be replaced by one <TextView/> and a compound drawable
- JavaScript 中的 this
- [TypeScript] Catch unsafe use of "this" in TypeScript functions
- This version of Android Studio cannot open this project, please retry with Android Studio 4.0 or newer.
- RF使用ie浏览器访问页面,浏览器启动只显示This is the initial start page for the WebDriver server,页面访问失败
- Javascript中this关键字详解
- 在Form窗体中,this的应用
- JavaScript 内的 this 指向
- 如何讲清楚this指向?
- 错误消息 This computer doesn‘t have VT-X/AMD-v enabled
- No pubspec.yaml file found. This command should be run from the root of your Flutter project. Do not
- This Gradle plugin requires a newer IDE able to request IDE model level 3. For Android Studio this m
- 已解决HINT: This error might have occurred since this system does not have Windows Long Path support en
- Vue新窗口打开this.$router
- JS对象中的方法的this指向
- 在函数内部定义的函数 this 指向 undefined
- appium===报错adb server version (31) doesn’t match this client (39); killing…的解决办法
- 12.IDA-虚函数和虚表(vf代表虚函数,vf3代表this指向第三个函数)
- this指向
- ORA-00845: MEMORY_TARGET not supported on this system
- VS CODE编译器C程序报错解决办法:Unable to perform this action because the process is running
- ftp登录报错:530 This server does not allow plain FTP. You have to use FTP over TLS