为什么this.func不是函数?(构造函数内的方法,在构造函数内调用,提示这个方法不是函数)

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()后面的括号后浏览器就没出现错误提醒了。为什么
我脑子短路了

阅读 2.8k
3 个回答

首先,异步函数运行的时候,this已经不是当前对象了,而是window,所以setTimeout里面的this.sayName其值为undefined

然后,去掉括号之后仅仅表示取出这个引用的值,但是并不会对它做任何操作。
如果这个值不存在,那么取出的值就是undefined,然后就这么完了,当然也就不会出错。

你可以把这里改成这样,然后你再运行看看是什么结果:

setTimeout(function(){
   console.log(this.sayName);
},1000);
setTimeout(function() {
   this.sayName();
},1000)

注意到这里定义了一个匿名函数,所以这里面的 this 已经不是 Bird 中的 this 了,那个 this 应该是 window。

如果用 ES6 的箭头语法就对了

setTimeout(() => {
   this.sayName();
},1000)
function Bird(name){
    this.name = name;
    this.sayName = function(){
        console.log('hello '+this.name +' guys');
    }
    setTimeout(function(){
       this.sayName();
    }.bind(this),1000);
 }
var a = new Bird();
a.sayName();
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题