Thuộc tính constructor của String object trả về tham chiếu đến hàm tạo String đã tạo instance.
Ví dụ
<!DOCTYPE html>
<html>
<body>
<script>
var str = new String("Đây là chuỗi");
document.write("str.constructor: " + str.constructor);
// function String() { [native code] }
// Kiểm tra constructor
console.log(str.constructor === String); // true
console.log("test".constructor === String); // true (primitive tự wrap)
</script>
</body>
</html>
Lưu ý:
constructorlà property của prototype:String.prototype.constructor.- Primitive string cũng truy cập được
.constructornhờ auto-boxing. - Dùng
typeof str === 'string'hoặcstr instanceof String(chỉ true cho object) để kiểm tra kiểu.
String primitive vs String object:
| Đặc điểm | Primitive | Object (new String) |
|---|---|---|
| Tạo | "hello" | new String("hello") |
| typeof | "string" | "object" |
| constructor | String | String |
| instanceof String | false | true |
Khuyến nghị: Luôn dùng primitive string "text". Tránh new String().