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

箭头函数和普通函数的区别? #2

Open
sihai00 opened this issue Jul 19, 2019 · 0 comments
Open

箭头函数和普通函数的区别? #2

sihai00 opened this issue Jul 19, 2019 · 0 comments
Assignees

Comments

@sihai00
Copy link
Owner

sihai00 commented Jul 19, 2019

区别

  • 没有自己的this:箭头函数内部的this就是引用外层代码块的this
  • 不能作为构造函数:因为没有this
  • 没有arguments对象
  • 不可以使用yield命令

不适用的场景

  1. 定义对象内的函数
  2. 需要动态this
// 1.定义对象内的函数
var lives = 1
const cat = {
  lives: 9,
  jumps: () => {
    this.lives--;
  }
}
console.log(cat.jumps())
// 输出结果:1

// 2. 需要动态this
var button = document.getElementById('press');
button.addEventListener('click', () => {
  this.classList.toggle('on');
})
// 点击button后报错,因为this指向windows,没有toggle属性

参考

ECMAScript 6 入门 - 阮一峰

@sihai00 sihai00 self-assigned this Jul 19, 2019
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant