KHÔNG dùng arrow function cho:
- Method của object: Arrow function không có
thisriêng ->thistrỏ rawindow(hoặc undefined strict mode). - Constructor: Không thể dùng
newvới arrow function. - Cần
arguments,super,new.target: Arrow function không có các binding này. - Event handler cần
this= element: Dùng function thường hoặcbind.
Ví dụ sai
Dùng arrow function làm method add của object -> this.a undefined:
<!DOCTYPE html>
<html lang="vi">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>When not to use arrow</title>
<style>
body { font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif; }
.result { font-size: 20px; font-weight: 500; color: blueviolet; }
</style>
</head>
<body>
<h1>Khi KHÔNG nên dùng Arrow Function</h1>
<br />
<div class="result"></div>
<br />
<button class="Btn">GỌI METHOD</button>
<h3>Nhấn nút để gọi obj.add() - arrow function method (sai)</h3>
<script>
const btn = document.querySelector('.Btn');
const resEle = document.querySelector('.result');
const obj = {
a: 22,
b: 44,
// SAI: arrow function không có this của obj
add: () => {
return this.a + this.b; // this = window -> NaN
}
};
btn.addEventListener('click', () => {
resEle.textContent = `Tổng ${obj.a} + ${obj.b} = ${obj.add()}`; // NaN
});
</script>
</body>
</html>
Kết quả
Hiển thị: Tổng 22 + 44 = NaN (vì this.a, this.b là undefined trên window).
Sửa đúng: Dùng method shorthand add() { return this.a + this.b; } hoặc function expression add: function() {...}.