web-interview icon indicating copy to clipboard operation
web-interview copied to clipboard

[选择题] 49.(单选题)下面代码的输出是什么

Open qiilee opened this issue 5 years ago • 0 comments

var status = '🐰'
setTimeout(() => { 
    const status = '🐎'
    const data = { 
        status: '🐍'
        getStatus() {
            return this.status
        }
    }
    console.log(data.getStatus()) 
    console.log(data.getStatus.call(this)) 
}, 0)
A:'🐍' and '🐎'
B: '🐍' and '🐰'
C: '🐎' and '🐰'
D: '🐰' and '🐰'

答案:B

解析:

this关键字的指向取决于使用它的位置。在函数中,比如 getStatus,this指向的是调用它的对象,上述例子中data对象调用了 getStatus因此this指向的就是data对象,当我们打印this.status时,data对象 的 status属性被打印,即'🐍'。

使用call方法,可以更政this指向的对象。data.getStatus.call(this)是将this的指向由data对象更改为全局对象。在全局对象上,有一个名为 status的变量,其值为'🐰'。因此打印this.status时,会打印'🐰'

qiilee avatar Apr 15 '20 10:04 qiilee