JavaScript 中創建字符串主要有三種形式:字面量、String() 構造函數、new String()。它們在類型、原型鏈、性能、屬性共享行為上存在關鍵差異。本文詳細對比並給出最佳實踐建議。
// 1. 字面量(推薦,最常用)
var str1 = "hello";
var str2 = 'world';
var str3 = `template ${str1}`; // ES6 模板字面量
// 2. String() 構造函數(作為轉型函數,不帶 new)
var str4 = String(123); // "123"
var str5 = String(true); // "true"
// 3. new String() 創建包裝對象(極少直接使用)
var strObj = new String("hello"); // String {0:"h", 1:"e", 2:"l", 3:"l", 4:"o", length:5, [[PrimitiveValue]]:"hello"}
| 特性 | 字面量 / String() | new String() |
|---|---|---|
| typeof | "string" | "object" |
| instanceof String | false | true |
| 原型鏈 | String.prototype | String.prototype → Object.prototype |
| 屬性寫入 | 不可寫入自定義屬性(嚴格模式拋錯) | 可寫入自定義屬性 |
| 比較行為 | 值比較:"a" === "a" // true | 引用比較:new String("a") === new String("a") // false |
| 性能/內存 | 輕量,引擎優化(字符串驻留) | 創建對象開銷大,佔用更多內存 |
| 自動裝箱 | 讀取屬性/方法時臨時創建包裝對象,用完即銷毀 | 持久對象 |
var s = "hello";
s.length; // 5 — 引擎臨時 new String(s) 讀取 length,隨即銷毀
s.custom = 123; // 寫入屬性(非嚴格模式靜默失敗,嚴格模式 TypeError)
s.custom; // undefined — 臨時對象已銷毀
var o = new String("hello");
o.custom = 123; // 成功
o.custom; // 123 — 同一對象持久存在
var name = "Tom";
var msg = `Hello, ${name}!
Current time: ${new Date().toLocaleTimeString()}.`;
// 多行、插值、標籤模板,完全替代字符串拼接
String(val),不使用 new String(val)。new String(),除非極罕見需要在字符串實例上掛載持久屬性的元編程場景。===,避免包裝對象導致的引用比較陷阱。typeof "abc"; // "string"
typeof new String("abc"); // "object"
"abc" instanceof String; // false
new String("abc") instanceof String; // true
new String("abc") instanceof Object; // true
理解字符串字面量與包裝對象的本質區別,能避免類型判斷、比較、屬性操作等隱性 Bug。