Truyền cài đặt module thông qua closure trong JavaScript
Giả sử chúng ta có module sau:
;(function(root, type, amount) {
let parent = document.querySelector(root);
for (let i = 1; i <= amount; i++) {
let elem = document.createElement(type);
parent.append(elem);
}
})('#parent', 'p', 5);
Như bạn thấy, có ba cài đặt được truyền vào module này: selector của phần tử cha, kiểu phần tử cần tạo và số lượng phần tử.
Thông thường, các cài đặt như vậy được thực hiện dưới dạng một đối tượng:
let config = {
root: '#parent',
type: 'p',
amount: 5
}
Hãy truyền đối tượng của chúng ta làm tham số cho module:
;(function(config) {
let parent = document.querySelector(config.root);
for (let i = 1; i <= config.amount; i++) {
let elem = document.createElement(config.type);
parent.append(elem);
}
})(config);
Cách thông dụng hơn là thực hiện destructuring đối tượng chứa cài đặt:
;(function({root, type, amount}) {
let parent = document.querySelector(root);
for (let i = 1; i <= amount; i++) {
let elem = document.createElement(type);
parent.append(elem);
}
})(config);