Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> JavaScript

Ô nhiễm không gian tên toàn cục (Global Namespace Pollution) trong JavaScript


Global Namespace Pollution

Gây ra name collision (va chạm tên) - thường见 trong dự án lớn dùng nhiều thư viện JS.

Ví dụ thực tế

2 team A1, A2 viết file JS riêng:

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 nhúng cả 2

<html> <head> <script src="TeamA1.js"></script> <script src="TeamA2.js"></script> </head> <body> <div id="resultDiv"></div> <script> document.getElementById("resultDiv").innerHTML = new student("Rajendra", "prasad").getFullName(); </script> </body> </html>

Kết quả

Rajendra prasad undefined

Giải thích

JS không hỗ trợ function overloading. Hàm sau (TeamA2.js) ghi đè (override) hàm trước (TeamA1.js). Code gọi 2 tham số nhưng hàm hiện tại yêu cầu 3 → mname = undefined.

Nếu đổi thứ tự load script: TeamA2 trước, TeamA1 sau → kết quả "Rajendra prasad" (đúng 2 tham số).

Bài học: Không nên đổ mọi thứ vào global namespace. Nên dùng module pattern, IIFE, hoặc ES6 modules để隔离 scope.