javascript - 为什么this.func不是函数?(构造函数内的方法,在构造函数内调用,提示这个方法不是函数)
阿神
阿神 2017-04-11 13:31:07
[JavaScript讨论组]
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()后面的括号后浏览器就没出现错误提醒了。为什么
我脑子短路了

阿神
阿神

闭关修行中......

全部回复(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)
PHP中文网
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();
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号