prototype的一些事

时间:2022-01-28 18:46:19
<script type="text/javascript">
foo=function(){
this.mayName="Foo function"
alert(this.mayName)
};
foo.prototype.sayHello=function(){
alert(this.mayName)
console.log(foo.prototype)
};
foo.prototype.bar=function(){
setTimeout(this.sayHello,1000)
};
var f=new foo;
f.bar();
</script>

  在这个demo中,需要输入“Foo function”,但是在网页中一直输出undefined,却一直找不到原因,纠结了一阵子。

原来,是因为setTimeOut把this的指向给改变了,指向了widows,在此同时,如果在

 foo.prototype.bar=function(){
setTimeout(this.sayHello(),1000)
};

 this.sayHello后面加一个“()”就能把this指向给改回。

这个坑,你们遇到了么?