- 使用箭头函数定义对象的方法
// 例子 3-1
// bad
let foo = {
value: 1,
getValue: () => console.log(this.value)
}
foo.getValue(); // undefined
- 定义原型方法
// bad
function Foo() {
this.value = 1
}
Foo.prototype.getValue = () => console.log(this.value)
let foo = new Foo()
foo.getValue(); // undefined
- 作为事件的回调函数
// 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