Lỗi "not a constructor function" xảy ra khi ta cố gắng dùng một đối tượng hoặc biến như một constructor (với từ khóa new) mà nó thực chất không phải là constructor.
Ví dụ
<!DOCTYPE html> <html lang="vi"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Not a constructor</title> <style> body { font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif; } .result { font-size: 18px; font-weight: 500; color: rebeccapurple; } </style> </head> <body> <h1>Lỗi Not a constructor function</h1> <div class="result"></div> <button class="Btn">NHẤN VÀO ĐÂY</button> <h3>Nhấn nút để dùng biến như constructor</h3> <script> let resEle = document.querySelector(".result"); let BtnEle = document.querySelector(".Btn"); let b = 22; BtnEle.addEventListener("click", () => { try { new b(); } catch (err) { resEle.innerHTML = err; } }); </script> </body> </html>
Kết quả
Khi nhấn nút, bắt lỗi: TypeError: b is not a constructor
Chỉ các hàm (function) và class mới có thể dùng với new. Số, chuỗi, đối tượng thường, mảng, null, undefined... đều ném lỗi này. Cần kiểm tra typeof fn === 'function' trước khi dùng new fn() nếu không chắc chắn.