Anonymous functions được dùng để gói gọn các đoạn code, thư viện JavaScript, hàm, v.v. để kiểm soát khả năng nhìn thấy và namespace, tránh xung đột với code của thư viện khác. IIFE (Immediately Invoked Function Expressions) được dùng cho mục đích này.
Dưới đây là mã triển khai Anonymous Wrapper Functions trong JavaScript:
Ví dụ
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Document</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>Anonymous wrapper functions in JavaScript</h1> <div class="result">0</div> <br /> <script> let resEle = document.querySelector(".result"); (function () { resEle.innerHTML = "Đoạn code này tự động thực thi vì nó nằm trong IIFE"; })(); </script> </body> </html>
Kết quả
