function Bird(name){
this.name = name;
this.sayName = function(){
console.log('hello '+this.name +' guys');
}
setTimeout(function(){
this.sayName();
},1000);
}
var a = new Bird();
a.sayName();
Uncaught TypeError: this.sayName is not a function
我指setTimeout上调用的this.sayName().
如果它指window对象上没有sayName函数我还能理解,但是去掉this.sayName()后面的括号后浏览器就没出现错误提醒了。为什么
我脑子短路了
首先,异步函数运行的时候,
this
已经不是当前对象了,而是window
,所以setTimeout
里面的this.sayName
其值为undefined
。然后,去掉括号之后仅仅表示取出这个引用的值,但是并不会对它做任何操作。
如果这个值不存在,那么取出的值就是
undefined
,然后就这么完了,当然也就不会出错。你可以把这里改成这样,然后你再运行看看是什么结果: