刚刚在一个面试题中看到一个这样的题目,指出下面一段js的问题所在:
- var Obj=function(msg){
- this.msg=msg;
- this.shout=function(){
- alert(this.msg);
- }
- this.waitAndShout=function(){
-
- setTimeout(this.shout, 2000);
- }
- }
- var aa=new Obj("abc");
- aa.waitAndShout();
我的回答是这样的
this.waitAndShot=function(){
setTimeout( function(){
this.shout();
},2000);
}
原因就是this.shout,返回的是函数的引用,即对象的方法。而this.shout()将会立即执行函数,setTimeout()是以普通函数执行的。