Skip to content
Share
Explore

Arrow Function

Arrow Function là gì?

Là cú pháp rút gọn để khai báo function, được giới thiệu từ ES6 (2015).
Viết ngắn hơn function() { ... }.
Dùng nhiều trong callback (.then, .map, .filter, …).
Ví dụ:

Khai báo Arrow Function

Function bình thường

Arrow Function

Arrow Function rút gọn hơn, nếu chỉ có 1 lệnh return

Dùng Arrow Function như callback (không cần khai báo)

Dùng Fn bình thường

Dùng Arrow Fn

Dùng Arrow Fn rút gọn nhất

Function lồng Function

Lưu ý

Arrow Fn giúp code gọn hơn, đặc biệt khi viết callback.
Giống fn bình thường với những hạn chế:
Phải viết trước khi sử dụng
// arrow fn KHÔNG ĐƯỢC lưu vào memory như 'var' hay fn bình thường
// arrow fn được thực thi theo thứ tự sau khi init, nên phải đứng trước khi gọi
regular();
arrow();

function regular() {
console.log('Regular');
}

const arrow = () => console.log('arrow');
không access được ‘this’, không tồn tại
// With normal functions, the `this` variable is created which references the objects that call them. Arrow functions do not create their own `this` binding.
const person = {
name: 'Brad',
sayHelloRegular: function () {
console.log('Regular:', this.name); // Regular Brad
},
sayHelloArrow: () => {
console.log('Arrow:', this.name); // undefined 'name'
},
};
Run the code and you get:
the ‘person’ object for the regular function
Because the arrow function does not automatically create a `this` variable, any reference to this would point to what this was before the function was created:
In Node with ES Modules, it's an empty object
in the browser, it's the `window` object.

Want to print your doc?
This is not the way.
Try clicking the ··· in the right corner or using a keyboard shortcut (
CtrlP
) instead.