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:
|
function show(){
alert("progressive");
}
setTimeout(show,1000);
or
setTimeout("show()",1000);
or
setTimeout("alert('progressive');",1000);