[英]JavaScript - Why can't I add new attributes to a “string” object?
我已經嘗試過JavaScript並注意到這個奇怪的事情:
var s = "hello world!";
s.x = 5;
console.log(s.x); //undefined
JavaScript中的每種類型的變量都是從對象繼承而來的。 因此應該可以為每個對象添加新屬性。
我誤解了什么不對嗎?
JavaScript中的字符串不是String
的實例。 如果你做了new String('my string')
那么它就是。 否則它是一個原語,當你在其上調用方法時,它會動態轉換為String
對象。 如果要獲取字符串的值,則需要調用toString()
,如下所示:
var s = new String("hello world!");
s.x = 5;
console.log(s.x); //5
console.log(s); //[object Object]
console.log(s.toString()); //hello world!
字符串對象是對象,可以展開,但字符串文字不是字符串對象,不能展開。
例:
var s = 'asdf';
s.x = 42;
alert(s.x); // shows "undefined"
s = new String('asdf');
s.x = 1337;
alert(s.x); // shows "1337"
Skilldrick的答案解釋了為什么它不起作用,因此回答了你的問題。
作為一個方面說明,這是可以做到這一點:
var s = {
toString: function() { return "hello world!"; }
};
s.x = 5;
console.log(s.x); // 5
console.log('result: ' + s); // "result: hello world!";
console.log(String(s)); // "hello world!";
你的s
是一個字符串文字,而不是一個字符串對象。 字符串文字的處理方式不同 :
無法向字符串文字添加屬性或方法的原因是,當您嘗試訪問文字的屬性或方法時,Javascript解釋器會臨時將字符串的值復制到新對象中,然后使用該對象的屬性或方法。 這意味着String文字只能訪問字符串的默認屬性或方法以及已添加為原型的字符串。
基元MDC文檔是不可變的。
原始的,原始的價值
不是對象且沒有任何方法的數據。
JavaScript有5種原始數據類型: string , number , boolean , null , undefined 。
除了null和undefined之外 ,所有基元值都具有包圍原始值的對象等價物,例如String對象環繞字符串基元。
所有原語都是不可變的 。
嘗試這樣做:
var s = "hello world!";
s.prototype.x = 5;
console.log(s.x);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.