Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
Genzhen opened this issue Jun 22, 2020 · 5 comments
Open

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

Genzhen opened this issue Jun 22, 2020 · 5 comments

Comments

@Genzhen
Copy link
Collaborator

Genzhen commented Jun 22, 2020

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

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

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

@Genzhen Genzhen changed the title Day18:写出执行结果,并解释原因 Day18:写出执行结果,并解释原因 Jun 22, 2020
@Genzhen
Copy link
Collaborator Author

Genzhen commented Jun 22, 2020

答案
12 NaN

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

@Genzhen Genzhen closed this as completed Jul 21, 2020
@Genzhen Genzhen reopened this Jul 29, 2020
@a123456789B
Copy link

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

@userkang
Copy link

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

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

@wind8866
Copy link

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

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

@jasonjiang123
Copy link

测试为-1

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

5 participants