Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> JavaScript

ทำไมต้องห่อ JavaScript ทั้งไฟล์ใน Anonymous Function (IIFE)

การห่อโค้ด JavaScript ทั้งไฟล์ใน IIFE (Immediately Invoked Function Expression) หรือ Self-Executing Anonymous Function มีจุดประสงค์หลักเพื่อสร้าง Namespace และควบคุม Visibility ของตัวแปรและฟังก์ชัน

ไวยากรณ์ (Syntax)

(function() {
  // code
})();

การทำงานแยกส่วน

  1. function() { ... } - Function Expression
  2. ( ... ) - วงเล็บครอบ แปลงเป็น Expression
  3. () - เรียกใช้ทันที

ตัวอย่างเปรียบเทียบ

ไม่ใช้ IIFE (มีปัญหา Global Pollution)

// file1.js
var userName = 'John';
function greet() { console.log('Hello ' + userName); }

// file2.js
var userName = 'Jane'; // ชนกับ file1!
function greet() { console.log('Hi ' + userName); } // ทับฟังก์ชันเดิม!

ใช้ IIFE (แยก Scope ชัดเจน)

// file1.js
(function() {
  var userName = 'John';
  function greet() { console.log('Hello ' + userName); }
  window.greetUser1 = greet; // expose เฉพาะที่ต้องการ
})();

// file2.js
(function() {
  var userName = 'Jane';
  function greet() { console.log('Hi ' + userName); }
  window.greetUser2 = greet;
})();

// ใช้งาน
greetUser1(); // Hello John
greetUser2(); // Hi Jane

รูปแบบ Module Pattern (Revealing Module)

var MyModule = (function() {
  // Private
  var privateVar = 0;
  function privateFunc() { console.log('private'); }
  
  // Public
  function publicFunc() { 
    privateVar++;
    console.log('public: ' + privateVar);
  }
  
  return {
    publicFunc: publicFunc
  };
})();

MyModule.publicFunc(); // public: 1
MyModule.publicFunc(); // public: 2
// MyModule.privateVar -> undefined (เข้าถึงไม่ได้)

ในยุค ES6+ (Modern Alternative)

ตอนนี้ใช้ ES Modules แทนได้แล้ว:

// utils.js
export function helper() { ... }
export const CONST = 'value';

// main.js
import { helper, CONST } from './utils.js';

ข้อดีของ ES Modules: Static analysis, Tree shaking, Browser native, Better tooling support

สรุป

วิธียุคข้อดีข้อเสีย
IIFEES5ทำงานในเบราว์เซอร์เก่า ได้เลยManual dependency management
CommonJSNode.jsSync, ใช้ใน Nodeต้อง bundler สำหรับเบราว์เซอร์
ES ModulesES6+Standard, Static, Tree-shakableต้องมี build step สำหรับเบราว์เซอร์เก่า