1.定义对象上的方法
const calculate = {
array: [1, 2, 3],
sum: () => {
console.log(this === window); // => true
return this.array.reduce((result, item) => result + item);
}
};
2。Object prototype
同样的规则也适用于在原型对象上定义方法。使用一个箭头函数来定义sayCatName方法,this 指向 window
function MyCat(name) {
this.catName = name;
}
MyCat.prototype.sayCatName = () => {
console.log(this === window); // => true
return this.catName;
};
const cat = new MyCat(‘Mew’);
cat.sayCatName(); // => undefined
3. 动态上下文的回调函数
const button = document.getElementById(‘myButton’);
button.addEventListener(‘click’, () => {
console.log(this === window); // => true
this.innerHTML = ‘Clicked button’;
});
4.调用构造函数
const Message = (text) => {
this.text = text;
};
// Throws “TypeError: Message is not a constructor”
const helloMessage = new Message(‘Hello World!’);