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

Câu lệnh WITH trong JavaScript (Deprecated)


with (obj) { ... } thêm obj vào đầu scope chain, cho phép truy cập property không cần prefix. Đã deprecated (Strict mode cấm) do: khó tối ưu, dễ gây bug (ambiguity), security risk. Không dùng trong code hiện đại.

Ví dụ (chỉ để hiểu)

Dùng with truy cập firstName, lastName của obj:

<!DOCTYPE html>
<html lang="vi">
<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <title>with statement JS</title>
  <style>
    body { font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif; }
    .result { font-size: 20px; font-weight: 500; color: green; }
  </style>
</head>
<body>
  <h1>Câu lệnh WITH trong JavaScript (Deprecated - Không nên dùng)</h1>
  <div class="result"></div>
  <button class="Btn">THỬ WITH</button>
  <h3>Nhấn để xem with(obj) truy cập property không prefix</h3>
  <script>
    const resEle = document.querySelector('.result');
    const btn = document.querySelector('.Btn');
    const obj = { firstName: 'Rohan', lastName: 'Sharma' };
    btn.addEventListener('click', () => {
      // Chỉ chạy ở non-strict mode
      with (obj) {
        resEle.textContent = `Welcome ${firstName} ${lastName}`;
      }
    });
  </script>
</body>
</html>

Kết quả

Hiển thị: Welcome Rohan Sharma (nếu browser cho phép non-strict).

Thay thế: Dùng destructuring const {firstName, lastName} = obj; hoặc gán biến cục bộ.