Global Namespace Pollution
การประกาศ Variable/Function ใน Global Scope มากเกินไป → Name Collision (ชื่อซ้ำ) โดยเฉพาะโปรเจกต์ใหญ่/หลายทีม/หลาย Library
ปัญหา: Name Collision ตัวอย่าง
TeamA1.js
function Student(fname, lname) {
this.fname = fname;
this.lname = lname;
this.getFullName = function() {
return this.fname + ' ' + this.lname;
};
}
TeamA2.js
function Student(fname, mname, lname) {
this.fname = fname;
this.mname = mname;
this.lname = lname;
this.getFullName = function() {
return this.fname + ' ' + this.mname + ' ' + this.lname;
};
}
HTML (Load ทั้งคู่)
<html> <head>
<script src="TeamA1.js"></script>
<script src="TeamA2.js"></script>
</head> <body>
<div id="result"></div>
<script>
document.getElementById('result').innerHTML =
new Student('Rajendra', 'Prasad').getFullName();
</script>
</body> </html>
ผลลัพธ์
Rajendra Prasad undefined
เหตุผล
- JavaScript ไม่รองรับ Function Overloading
- TeamA2.js โหลดทีหลัง → Override TeamA1.js
- Function Student รับ 3 Parameters แต่ส่ง 2 → mname = undefined
วิธีป้องกัน (Best Practices)
1. IIFE (Immediately Invoked Function Expression)
// TeamA1.js
(function() {
function Student(fname, lname) { ... }
window.TeamA1 = { Student }; // Export เฉพาะที่ต้องการ
})();
2. Module Pattern / Namespace
var MyApp = MyApp || {};
MyApp.Models = MyApp.Models || {};
MyApp.Models.Student = function(fname, lname) { ... };
3. ES Modules (Modern Standard)
// student.js
export class Student { constructor(fname, lname) { ... } }
// main.js
import { Student } from './student.js';
4. Strict Mode
'use strict';
// Undeclared Assignment → ReferenceError
สรุป
- Global Scope = Shared Resource → Conflict ง่าย
- ใช้ Module System (ESM) เป็นหลัก
- Legacy: IIFE + Namespace Object
- Build Tools (Webpack, Vite, Rollup) จัดการ Scope ให้อัตโนมัติ