javascript - js this 问题
PHP中文网
PHP中文网 2017-04-11 09:11:59
[JavaScript讨论组]
class Animal {
    constructor(){
        console.log(this);
        this.type = 'animal'
    }
    says(say){
        setTimeout(function(){
            console.log(this);
            console.log(this.type + ' says ' + say)
        }, 1000)
    }
}

为什么一个this是Animal对象,一个this是window对象?

PHP中文网
PHP中文网

认证高级PHP讲师

全部回复(5)
伊谢尔伦

这是JS中一个不好的地方: setTimeout的执行上下文是window对象而不是class Animal. 导致了setTimeout中的函数是基于全局作用域执行, 其中的this指向了window
可以这样解决(ES6):

setTimeout(() => {
    // you code...
    }, 1000)
ringa_lee

setTimeout 里面 的匿名函数是作为函数调用的,而不是 对象的方法。。而作为函数调用的this 就是指向全局啊。。而不是setTimeout剥离你的上下文。。。里面就是个函数,不信你可以这么写。

 says(say){
        function test(){
            console.log(this);
            console.log(this.type + ' says ' + say)
        }
        test();//这个this 绝对也不是指向Animal对象
    }
PHP中文网

一.

 says(say){
        var _this = this;
        setTimeout(function(){
            console.log(_this);
            console.log(_this.type + ' says ' + say)
        }, 1000)
    }
大家讲道理

JS中函数内的上下文是由函数的调用者决定的,setTimeout的调用者是window,所以会log出window。这里如楼上所说,是可以使用箭头函数解决的,因为箭头函数的上下文是其所处环境决定的。

伊谢尔伦

闭包,函数嵌套函数,可以访问函数中的局部变量

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

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