Javascript对象中关于setTimeout和setInterval的this介绍
时间:2024-04-17 09:55:15
在Javascript里,setTimeout和setInterval接收第一个参数是一个字符串或者一个函数,当在一个对象里面用setTimeout延时调用该对象的方法时
function obj() {
this.fn = function() {
alert("ok");
console.log(this);
setTimeout(this.fn, 1000);//直接使用this引用当前对象
}
}
var o = new obj();
o.fn();
然后我们发现上面的代码不是想要的结果,原因是setTimeout里面的this是指向window,所以要调用的函数变成 window.fn 为undefined,于是悲剧了。所以问题的关键在于得到当前对象的引用,于是有以下三种方法
// 方法一:
function obj() {
this.fn = function() {
alert("ok");
console.log(this);
setTimeout(this.fn.bind(this), 1000);//通过Function.prototype.bind 绑定当前对象
}
}
var o = new obj();
o.fn();
这样可以得到正确的结果,可惜Function.prototype.bind方法是ES5新增的标准,测试了IE系列发现IE6-8都不支持,只有IE9+可以使用。要想兼容就得简单的模拟下bind,看下面的代码
// 方法二:
function obj() {
this.fn = function() {
alert("ok");
setTimeout((function(a,b){
return function(){
b.call(a);
}
})(this,this.fn), 1000);//模拟Function.prototype.bind
}
}
var o = new obj();
o.fn();
首先通过一个自执行匿名函数传当前对象和对象方法进去,也就是里面的参数a和b,再返回一个闭包,通过call方法使this指向正确。下面是比较简洁的方法
// 方法三:
function obj() {
this.fn = function() {
var that = this;//保存当前对象this
alert("ok");
setTimeout(function(){
that.fn();
}, 1000);//通过闭包得到当前作用域,好访问保存好的对象that
}
}
var o = new obj();
o.fn();
上面第三个方法的两个关键点是 保存当前对象this为别名that 和 通过闭包得到当前作用域,以访问保存好的对象that;当对象方法里面多层嵌套函数或者setTimeout,setInterval等方法丢失this(也就是this不指向当前对象而是window),所以在this指向正确的作用域保存var that = this就变得很实用了
标签:setTimeout,setInterval,this
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
.NET Core读取配置文件的方法
2024-06-05 09:31:38
PHP清除缓存的几种方法总结
2024-06-05 15:32:34
![](https://img.aspxhome.com/file/2023/3/122853_0s.jpg)
详解Python判定IP地址合法性的三种方法
2021-12-02 14:35:10
Mysql中TIMESTAMPDIFF函数的语法与练习案例
2024-01-28 18:43:44
![](https://img.aspxhome.com/file/2023/7/128067_0s.png)
python 图像增强算法实现详解
2023-10-27 10:12:47
![](https://img.aspxhome.com/file/2023/1/85161_0s.png)
python图片指定区域替换img.paste函数的使用
2023-10-17 02:34:01
![](https://img.aspxhome.com/file/2023/3/131303_0s.jpg)
mysql复制表的几种常用方式总结
2024-01-25 12:11:59
![](https://img.aspxhome.com/file/2023/9/107429_0s.png)
SQL Server在T-SQL语句中使用变量
2024-01-21 10:21:34
python爬虫可以爬什么
2022-05-26 01:24:31
NumPy 如何生成多维数组的方法
2022-06-26 20:40:51
Python为人脸照片添加口罩实战
2021-11-12 23:39:33
![](https://img.aspxhome.com/file/2023/3/67313_0s.jpg)
详细讲解Python中的文件I/O操作
2022-01-01 19:04:53
![](https://img.aspxhome.com/file/2023/0/92230_0s.jpg)
浅谈Selenium 控制浏览器的常用方法
2022-03-30 04:40:33
Django csrf校验的实现
2023-10-01 14:49:40
![](https://img.aspxhome.com/file/2023/9/72929_0s.png)
golang操作elasticsearch的实现
2024-02-04 08:42:45
![](https://img.aspxhome.com/file/2023/0/105100_0s.png)
Python常用Web框架Django、Flask与Tornado介绍
2021-06-24 18:19:35
PYcharm 激活方法(推荐)
2022-07-27 01:51:21
![](https://img.aspxhome.com/file/2023/9/123809_0s.jpg)
DreamWeaver操作超级技巧大全
2008-10-03 20:50:00
对Python3使运行暂停的方法详解
2021-02-05 22:55:21
![](https://img.aspxhome.com/file/2023/8/82738_0s.jpg)
浅析location.href跨窗口调用函数
2024-04-17 09:41:37