Skip to content

Day18:写出执行结果,并解释原因 #54

@Genzhen

Description

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

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

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

Activity

changed the title [-]Day18:写出执行结果,并解释原因[/-] [+]Day18:写出执行结果,并解释原因[/+] on Jun 22, 2020
Genzhen

Genzhen commented on Jun 22, 2020

@Genzhen
CollaboratorAuthor

答案
12 NaN

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

a123456789B

a123456789B commented on Sep 4, 2020

@a123456789B

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

userkang

userkang commented on Jan 15, 2021

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

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

wind8866

wind8866 commented on Jun 30, 2021

@wind8866

我本来以为严格模式下 this 不能指向全局对象,没想到箭头函数是可以的。

function f(){
  console.log(this);
}
f();// undefined
const f2 = () => {
  console.log(this);
}
f2();// window
jasonjiang123

jasonjiang123 commented on Aug 2, 2021

@jasonjiang123

测试为-1

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

      Development

      No branches or pull requests

        Participants

        @jasonjiang123@userkang@Genzhen@a123456789B@wind8866

        Issue actions

          Day18:写出执行结果,并解释原因 · Issue #54 · lgwebdream/FE-Interview