ใช้ string.constructor คืน reference ไปยัง String function ที่สร้าง instance's prototype
ตัวอย่าง
<html>
<head>
<title>JavaScript String constructor Method</title>
</head>
<body>
<script>
var str = new String("This is string");
document.write("str.constructor is: " + str.constructor);
</script>
</body>
</html>
ผลลัพธ์
str.constructor is: function String() { [native code] }
String Constructor Patterns
// 1. String primitive (แนะนำ)
var str1 = "hello";
// 2. String object (ไม่แนะนำ)
var str2 = new String("hello");
// 3. String() as function (แปลงเป็น primitive)
var str3 = String(123); // "123"
var str4 = String(true); // "true"
var str5 = String(null); // "null"
var str6 = String(undefined); // "undefined"
ความแตกต่าง Primitive vs Object
| Aspect | Primitive | Object (new String) |
|---|---|---|
| typeof | "string" | "object" |
| Performance | เร็วกว่า | ช้ากว่า |
| Methods | Auto-boxing (มีครบ) | มีครบ |
| === comparison | value | reference |
แนะนำ: ใช้ primitive string "hello" เสมอ หลีกเลี่ยง new String()