-
Notifications
You must be signed in to change notification settings - Fork 891
Open
Description
const num = {
a: 10,
add() {
return this.a + 2;
},
reduce: () => this.a -2
};
console.log(num.add());
console.log(num.reduce());
每日一题会在下午四点在交流群集中讨论,五点小程序中更新答案
欢迎大家在下方发表自己的优质见解
二维码加载失败可点击 小程序二维码
Activity
[-]Day18:写出执行结果,并解释原因[/-][+]Day18:写出执行结果,并解释原因[/+]Genzhen commentedon Jun 22, 2020
答案
12 NaN
解析
注意,add是普通函数,而reduce是箭头函数。对于箭头函数,
this
关键字指向是它所在上下文(定义时的位置)的环境,与普通函数不同! 这意味着当我们调用reduce时,它不是指向num对象,而是指其定义时的环境(window)。没有值a属性,返回undefined
。a123456789B commentedon Sep 4, 2020
答案
12 NaN
reduce: () => this.a -2; 箭头函数中的this 指向外层正常函数,因为外层没有函数所以指向window ,window中没有a ,返回undefind 加上number 所以为NaN
userkang commentedon Jan 15, 2021
这行代码最后一行的
;
多余了wind8866 commentedon Jun 30, 2021
我本来以为严格模式下 this 不能指向全局对象,没想到箭头函数是可以的。
jasonjiang123 commentedon Aug 2, 2021
测试为-1