Heim  >  Artikel  >  Web-Frontend  >  Javascript对象中关于setTimeout和setInterval的this介绍_javascript技巧

Javascript对象中关于setTimeout和setInterval的this介绍_javascript技巧

WBOY
WBOYOriginal
2016-05-16 17:51:45994Durchsuche

在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就变得很实用了
Stellungnahme:
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn