js setTimeout 在类中,绑定this的方法

本文探讨了JavaScript中setTimeout函数的使用,特别是当其应用于类方法时,导致this指向window的问题。提供了两种解决方案:一是使用call方法绑定上下文;二是通过代理函数保持正确的this上下文。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

setTimeout 最常用的用法是:


setTimeout(functionName,1000); //functionName 为一个函数的名字


在一个类中,调用setTimeout,会出现问题,this指向了window

var firstName = "zhengxiang";
var name ={
   firstName : "xiong",
   showName : function(){
        alert(this.firstName);
   },
   waitShowName : function(){
        setTimeout(this.showName,1000);
   }
};
name.waitShowName();      //输出zhengxiang


//通过下面的例子,也可以看到setTimeout 的函数中,this指向的是window

(function () {
  alert(this); // alerts hello
  setTimeout(function(){
    alert(this == window); // true
  }, 1000);
}).call("hello");


解决this指向window,而非指向类对象的问题,常用以下两个方法

第一:

//使用call,将函数的运行环境绑定到类上面

var Bind = function(object, func) {
	return function() {
		return func.apply(object, arguments);
	}
}

例如:

var firstName = "zhengxiang";
var name ={
   firstName : "xiong",
   showName : function(){
        alert(this.firstName);
   },
   bind : function(object, func) {
	return function() {
		return func.apply(object, arguments);
	}
   },
   waitShowName : function(){
        setTimeout(this.bind(this,this.showName),1000);
   }
};
name.waitShowName();//输出:xiong

第二种方法:

利用代理函数,利用外围保存的this环境that,调用函数

var firstName = "zhengxiang";
var name ={
   firstName : "xiong",
   showName : function(){
        alert(this.firstName);
   },
   bind : function(object, func) {
	return function() {
		return func.apply(object, arguments);
	}
   },
   waitShowName : function(){
        var that = this;    
        setTimeout(function(){that.showName();},1000);
   }
};
name.waitShowName();//输出:xiong

附:setTimeout的用法:

window.setTimeout(vCode, iMilliSeconds [, sLanguage])
Parameters

vCode
Required. Variant that specifies the function pointer or string that indicates the code to be executed when the specified interval has elapsed.
iMilliSeconds
Required. Integer that specifies the number of milliseconds.
sLanguage
Optional. String that specifies one of the following values:
JScript
Language is JScript.
VBScript
Language is VBScript.
JavaScript
Language is JavaScript.
所以:

function show(){

     alert("progressive");

}

setTimeout(show,1000);

or

setTimeout("show()",1000);

or

setTimeout("alert('progressive');",1000);



评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值