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

วิธีประกาศ Namespace ใน JavaScript

JavaScript ใช้คีย์เวิร์ด var เพื่อประกาศ namespace วิธีประกาศ namespace ใน JavaScript:

var myNamespace = { 
  functionOne: function() { 
  }, 
  functionTwo: function() { 
  } 
}; 
// เรียกใช้
myNamespace.functionOne();

Namespace Patterns ใน JavaScript

// 1. Object Literal (Simple Namespace)
const MyApp = {
  utils: {
    formatDate(date) { return date.toISOString(); },
    validateEmail(email) { return /\S+@\S+\.\S+/.test(email); }
  },
  api: {
    baseUrl: '/api/v1',
    async fetch(endpoint) { /* ... */ }
  }
};

// 2. IIFE Module Pattern (Encapsulation)
const MyModule = (function() {
  let privateVar = 0;  // private
  
  function privateHelper() { /* ... */ }
  
  return {
    publicMethod() { 
      privateVar++;
      return privateVar;
    },
    getValue() { return privateVar; }
  };
})();

// 3. ES Modules (Modern Standard - แนะนำ)
// file: utils.js
export function formatDate(date) { return date.toISOString(); }
export const API_URL = '/api';

// file: main.js
import { formatDate, API_URL } from './utils.js';

Best Practices

  • ใช้ ES Modules (import/export) เป็นมาตรฐานปัจจุบัน — แต่ละไฟล์เป็น module scope เอง
  • หลีกเลี่ยง global namespace pollution
  • ตั้งชื่อ namespace ให้ unique (เช่น ชื่อบริษัท/โปรเจกต์)
  • ใช้ const สำหรับ namespace object