JavaScript 匿名包裝函式
匿名函式用於包裝程式碼片段、JavaScript 庫、函式等,以控制它們的可視性和名稱空間,這樣就不會與其他庫程式碼發生衝突。IIFE(立即執行函式表示式)用於此目的。
以下程式碼在 JavaScript 中實現匿名包裝函式:
示例
<!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 = "This piece of code is automatically executed as it is inside an IIFE"; })(); </script> </body> </html>
輸出
廣告