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

Constructor tạo đối tượng String trong JavaScript?

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 ý:

  • constructor là property của prototype: String.prototype.constructor.
  • Primitive string cũng truy cập được .constructor nhờ auto-boxing.
  • Dùng typeof str === 'string' hoặc str instanceof String (chỉ true cho object) để kiểm tra kiểu.

String primitive vs String object:

Đặc điểmPrimitiveObject (new String)
Tạo"hello"new String("hello")
typeof"string""object"
constructorStringString
instanceof Stringfalsetrue

Khuyến nghị: Luôn dùng primitive string "text". Tránh new String().