Computer >> Máy Tính >  >> Lập trình >> Javascript

JavaScript Biểu thức hàm được gọi ngay lập tức (IIFE)

Biểu thức hàm được gọi ngay lập tức trong JavaScript (IIFE) là một hàm JavaScript thực thi ngay sau khi nó được xác định, do đó không cần gọi IIFE theo cách thủ công.

Sau đây là mã cho Biểu thức hàm được gọi ngay lập tức (IIFE) 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;
   }
   .sample {
      font-size: 18px;
      font-weight: 500;
   }
</style>
</head>
<body>
<h1>JavaScript Immediately Invoked Function Expressions (IIFE)</h1>
<div class="sample"></div>
<script>
   let sampleEle = document.querySelector(".sample");
   (function () {
      sampleEle.innerHTML ="This code is invoked immediately as soon as it is defined";
   })();
</script>
</body>
</html>

Đầu ra

JavaScript Biểu thức hàm được gọi ngay lập tức (IIFE)