Fe-interview: Day18:写出执行结果,并解释原因

Created on 22 Jun 2020  ·  3Comments  ·  Source: lgwebdream/FE-Interview

const num = {
  a: 10,
  add() {
    return this.a + 2;
  },
  reduce: () => this.a -2
};
console.log(num.add());
console.log(num.reduce());

每日一题会在下午四点在交流群集中讨论,五点小程序中更新答案
欢迎大家在下方发表自己的优质见解
二维码加载失败可点击 小程序二维码

扫描下方二维码,收藏关注,及时获取答案以及详细解析,同时可解锁800+道前端面试题。

Most helpful comment

reduce: () => this.a -2;

这行代码最后一行的 ; 多余了

All 3 comments

答案
12 NaN

解析
注意,add是普通函数,而reduce是箭头函数。对于箭头函数,this关键字指向是它所在上下文(定义时的位置)的环境,与普通函数不同! 这意味着当我们调用reduce时,它不是指向num对象,而是指其定义时的环境(window)。没有值a属性,返回undefined

答案
12 NaN
reduce: () => this.a -2; 箭头函数中的this 指向外层正常函数,因为外层没有函数所以指向window ,window中没有a ,返回undefind 加上number 所以为NaN

reduce: () => this.a -2;

这行代码最后一行的 ; 多余了

Was this page helpful?
0 / 5 - 0 ratings