我已經嘗試了JavaScript和注意到了這個奇怪的事情:JavaScript - 爲什麼我不能將新屬性添加到「字符串」對象?
var s = "hello world!";
s.x = 5;
console.log(s.x); //undefined
在JavaScript中每一個類型的變量是從對象繼承。所以應該可以爲每個對象添加新的屬性。
我誤解了錯誤嗎?
我已經嘗試了JavaScript和注意到了這個奇怪的事情: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!
謝謝!我從來沒有注意到「hello」和new String(「hello」)之間有區別。我登錄了「hello」.__ proto__並獲得了Object。所以我很清楚...... – 2011-04-04 13:27:39
String對象是對象和可擴展的,但字符串文字不是字符串對象,不能擴大。
例子:
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
是一個字符串,而不是字符串對象。字符串文字handled differently:
The reason you can't add properties or methods to a string literal is that when you try to access a literal's property or method, the Javascript interpreter temporarily copies the value of the string into a new object and then use that object's properties or methods. This means a String literal can only access a string's default properties or methods and those that have been added as prototypes.
這是一個報價?如果是這樣,從哪裏? – 2011-04-04 13:36:13
是的,這是一個報價。引用鏈接在報價之前。 – 2011-04-04 13:38:50
啊,對不起。我是個白癡。 – 2011-04-04 13:39:24
Primitives MDC docs是不可改變的。
primitive, primitive value
A data that is not an object and does not have any methods.
JavaScript has 5 primitive datatypes: string, number, boolean, null, undefined.
With the exception of null and undefined, all primitives values have object equivalents which wrap around the primitive values, e.g. a String object wraps around a string primitive.
All primitives are immutable.
嘗試這樣做:
var s = "hello world!";
s.prototype.x = 5;
console.log(s.x);
這會將x屬性添加到所有字符串對象,而不是我想要做的;) – 2011-04-04 13:32:45
給出「TypeError:表達式結果's.prototype'[undefined]不是一個對象。」無論如何,即使s是一個字符串對象,對象也不會從它們自己的原型繼承,而是從內部的[[prototype]]屬性引用的構造函數繼承。 – RobG 2011-04-04 13:39:58
有原始類型不從'Object'繼承。這是字符串,數字和布爾文字的情況。 – 2011-04-04 13:22:36
JS最糟糕的語言型系統 – 2014-05-16 13:10:14