var Obj = function(msg){ this.msg = msg; this.shout = function(){ alert(this.msg); } this.waitAndShout = function(){ //隔五秒钟后执行上面的shout方法 } }
// 使用bind // this 指向全局变量 window var Obj = function(msg){ this.msg = msg; this.shout = function(){ alert(this.msg); } this.waitAndShout = function(){ setTimeout(function () { this.shout(); }.bind(this), 5000); } }
var Obj = function(msg){ this.msg = msg; this.shout = function(){ alert(this.msg); } this.waitAndShout = function(){ var that=this; setTimeout(function(){ that.shout(); },5000); } } var test=new Obj("a"); test.waitAndShout(); //setTimeout函数作用域
方法调用模式
函数调用模式
构造器调用模式
apply/call调用模式
var Obj = function(msg){ this.msg = msg; this.shout = function(){ console.log(this.msg); } this.waitAndShout = function(){ //隔五秒钟后执行上面的shout方法 var that=this; setTimeout(that.shout,5000); } return this; } var obj=Obj("woshimsg"); obj.waitAndShout();
var Obj = function(msg){ this.msg = msg; this.shout = function(){ alert(this.msg); }; this.waitAndShout = function(){ var that = this; setTimeout(function(){that.shout();},5000); //隔五秒钟后执行上面的shout方法 } return this; } Obj("shouting").waitAndShout();
var Obj = function(msg){
this.msg = msg;
this.shout = function(){ alert(this.msg); } this.waitAndShout = function(){ setTimeout(this.shout,5000);//隔五秒钟后执行上面的shout方法 } }
这道题你会答吗?花几分钟告诉大家答案吧!
扫描二维码,关注牛客网
下载牛客APP,随时随地刷题
this.msg = msg;
this.shout = function(){
alert(this.msg);
}
this.waitAndShout = function(){
var that = this;
setTimeout(that.shout, 5000);
//隔五秒钟后执行上面的shout方法
}
return this;
}
Obj("shouting").waitAndShout();