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()后面的括号后浏览器就没出现错误提醒了。为什么
我脑子短路了
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
首先,异步函数运行的时候,
this已经不是当前对象了,而是window,所以setTimeout里面的this.sayName其值为undefined。然后,去掉括号之后仅仅表示取出这个引用的值,但是并不会对它做任何操作。
如果这个值不存在,那么取出的值就是
undefined,然后就这么完了,当然也就不会出错。你可以把这里改成这样,然后你再运行看看是什么结果:
注意到这里定义了一个匿名函数,所以这里面的
this已经不是 Bird 中的this了,那个this应该是 window。如果用 ES6 的箭头语法就对了