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

Trả về giá trị từ Constructor trong JavaScript

Constructor trong JavaScript **tự động trả về this** (instance mới tạo). Tuy nhiên, có thể **ghi đè (override)** bằng cách return một **object** khác.

Quy tắc:

  • return **primitive** (string, number, boolean, null, undefined) → **bỏ qua**, trả về this
  • return **object** (object, array, function) → **trả về object đó**, this bị bỏ qua
  • Không có return hoặc return; → trả về this

Ví dụ minh họa

<!DOCTYPE html>
<html lang="vi">
<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <title>Return from Constructor</title>
  <style>
    body { font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif; padding: 20px; }
    .result { font-size: 18px; font-weight: 500; margin: 10px 0; color: green; }
    button { padding: 8px 16px; cursor: pointer; }
  </style>
</head>
<body>
  <h1>Trả về giá trị từ Constructor</h1>
  <div class="result" id="result"></div>
  <button class="Btn" id="btn">NHẤN VÀO ĐÂY</button>
  <h3> Nhấn nút để xem object trả về từ constructor </h3>
  <script>
    const resEle = document.querySelector("#result");
    
    function Human() {
      this.firstName = 'Rohan';
      this.lastName = 'Sharma';
      this.age = 22;
      // Trả về object khác -> ghi đè this
      return { firstName: 'Mohit', lastName: 'Sharma' };
    }
    
    const obj = new Human();
    
    document.querySelector("#btn").addEventListener("click", () => {
      for (const key in obj) {
        resEle.innerHTML += `Key = ${key} : Value = ${obj[key]}
`; } resEle.innerHTML += `
Constructor name: ${obj.constructor.name}`; resEle.innerHTML += `
instanceof Human: ${obj instanceof Human}`; // false! }); </script> </body> </html>

Kết quả

Key = firstName : Value = Mohit
Key = lastName : Value = Sharma

Constructor name: Object
instanceof Human: false

Phân tích:

  • Constructor Human set this.firstName = 'Rohan'
  • Nhưng return { firstName: 'Mohit', ... } ghi đè
  • Instance obj là object trả về, **KHÔNG phải instance của Human**
  • obj instanceof Human = false

Trường hợp return primitive (bỏ qua):

function Test() {
  this.name = "Original";
  return "primitive string"; // BỎ QUA
}
const t = new Test();
console.log(t.name); // "Original" - this được trả về

Ứng dụng thực tế (Factory pattern trong constructor):

function User(name, role) {
  // Validation
  if (!name) throw new Error("Name required");
  
  // Trả về object khác tùy role
  if (role === 'admin') {
    return { 
      name, 
      role: 'admin', 
      permissions: ['read', 'write', 'delete'],
      isAdmin: true
    };
  }
  
  // Default: trả về this (instance bình thường)
  this.name = name;
  this.role = 'user';
  this.permissions = ['read'];
}

const admin = new User("Alice", "admin"); // Object custom
const user = new User("Bob"); // Instance của User

console.log(admin instanceof User); // false
console.log(user instanceof User);  // true

⚠️ Cảnh báo:

  • Làm hỏng instanceof check
  • Prototype chain bị phá vỡ
  • Khó debug, khó hiểu
  • **Khuyên dùng Factory Function** thay vì hack constructor:

Factory Function Pattern (Khuyên dùng):

function createUser(name, role = 'user') {
  const base = { name, role };
  
  if (role === 'admin') {
    return { ...base, permissions: ['read','write','delete'], isAdmin: true };
  }
  
  return { ...base, permissions: ['read'], isAdmin: false };
}

const admin = createUser("Alice", "admin");
const user = createUser("Bob");
// Cả hai đều là plain object, consistent behavior