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

Cách sử dụng Boolean trong Constructor JavaScript?

Phương thức Boolean.prototype.constructor trả về tham chiếu đến hàm Boolean đã tạo instance.

Ví dụ

<!DOCTYPE html>
<html>
<body>
    <script>
        var bool = new Boolean();
        document.write("bool.constructor: " + bool.constructor);
        // function Boolean() { [native code] }
        
        // Kiểm tra
        console.log(bool.constructor === Boolean); // true
        console.log(true.constructor === Boolean); // true (primitive auto-wrap)
    </script>
</body>
</html>

Lưu ý:

  • constructor nằm trên Boolean.prototype.
  • Primitive boolean cũng truy cập được nhờ auto-boxing.
  • Ít khi dùng trực tiếp — chủ yếu dùng cho reflection/type checking.

Constructor Function Pattern (Tạo đối tượng tùy chỉnh):

function User(name, isActive) {
    this.name = name;
    this.isActive = Boolean(isActive); // Ép kiểu về boolean primitive
    // this.isActive = !!isActive; // Cách ngắn gọn
}

const user1 = new User("An", 1);     // isActive: true
const user2 = new User("Bình", 0);   // isActive: false
const user3 = new User("Cường", "yes"); // isActive: true (string không rỗng)

console.log(user1.isActive); // true (boolean)
console.log(typeof user1.isActive); // "boolean"

Khuyến nghị: Trong constructor, dùng Boolean() hoặc !! để chuẩn hóa về boolean primitive, không dùng new Boolean().