箭头使用箭头函数,不过以下几种情况避免使用:

2020-11-12  本文已影响0人  如果俞天阳会飞
  1. 使用箭头函数定义对象的方法
// 例子 3-1

// bad
let foo = {
  value: 1,
  getValue: () => console.log(this.value)
}

foo.getValue();  // undefined
  1. 定义原型方法
// bad
function Foo() {
  this.value = 1
}

Foo.prototype.getValue = () => console.log(this.value)

let foo = new Foo()
foo.getValue();  // undefined
  1. 作为事件的回调函数
// bad
const button = document.getElementById('myButton');
button.addEventListener('click', () => {
    console.log(this === window); // => true
    this.innerHTML = 'Clicked button';
});

例子

  var a = 2;
  const b = 'bbb';
  let foo = {
    a: 1,
    b:'b',
    getValue1: () => {
      console.log(this.a)
    },
    getValue2() {
      console.log(this.a)
    },
    getValue3: () => {
      console.log(this.b)
    },
  };

  foo.getValue1();  // 2
  foo.getValue2();  // 1
  foo.getValue3();  // undefined
  console.log([7].toString()) // 7
上一篇 下一篇

猜你喜欢

热点阅读