var name="XL"; function Person(name){ this.name=name; this.sayName=function(){ setTimeout(function(){ console.log("my name is "+this.name); },50) } } var person=new Person("xl"); person.sayName() //输出 “my name is XL”; //这里的setTimeout()定时函数,相当于window.setTimeout(),由window这个全局对象对调用,因此this的指向为window, 则this.name则为XL
;)
那么如何才能输出"my name is xl"呢?
;)
1 2 3 4 5 6 7 8 9 10 11
var name="XL"; function Person(name){ this.name=name; this.sayName=function(){ setTimeout(function(){ console.log("my name is "+this.name); }.bind(this),50) //注意这个地方使用的bind()方法,绑定setTimeout里面的匿名函数的this一直指向Person对象 } } var person=new Person("xl"); person.sayName(); //输出 “my name is xl”;
;)
这里setTimeout(function(){console.log(this.name)}.bind(this),50);,匿名函数使用bind(this)方法后创建了新的函数,这个新的函数不管在什么地方执行,this都指向的Person,而非window,因此最后的输出为”my name is xl”而不是”my name is XL”
var name="XL"; function Person(){ this.name="xl"; this.showName=function(){ console.log(this.name); } setTimeout(this.showName,50); } var person=new Person(); //输出 "XL" //在setTimeout(this.showName,50)语句中,会延时执行this.showName方法 //this.showName方法即构造函数Person()里面定义的方法。50ms后,执行this.showName方法,this.showName里面的this此时便指向了window对象。则会输出"XL";
;)
修改上面的代码:
;)
;)
1 2 3 4 5 6 7 8 9 10 11 12 13 14
var name="XL"; function Person(){ this.name="xl"; var that=this; this.showName=function(){ console.log(that.name); } setTimeout(this.showName,50) } var person=new Person(); //输出 "xl" //这里在Person函数当中将this赋值给that,即让that保存Person对象,因此在setTimeout(this.showName,50)执行过程当中,console.log(that.name)即会输出Person对象的属性"xl"