[英]Can not modify properties added to Number.prototype
有人可以用JavaScript解釋這種行為嗎?
var a = 6;
a.constructor.prototype.prop = 5;
print(a.prop);
a.prop = 4;
print(a.prop);
然后我在ideone中運行它:
5
5
我知道a
本身就是一個number
,但是它的原型是object
。 但是為什么存在這種差異呢? 當然,這可能是多個編碼錯誤的根源。 這是否被視為JavaScript的“邪惡部分”?
問題在於a
是原始值。 不是對象 您只能將屬性分配給對象。 不是原始值。
當您嘗試將屬性分配給原始值時,JavaScript立即將其強制為一個對象。 例如:
var x = true; // x is primitive
x.y = false; // x is coerced to an object
alert(x.y); // y is undefined
在此處查看演示: http : //jsfiddle.net/UtYkA/
第二行中發生的是:
new Boolean(x).y = false; // x is not the same as new Boolean(x)
因為x
被強制到一個對象中,並且屬性y
被添加到該對象,所以沒有將屬性添加到x
本身。
對於所有原語(JavaScript中的布爾值,數字和字符串)都是如此。 這是原因print(a.prop)
始終打印5
- a
是原始的,而不是一個對象。
當您嘗試訪問a.prop
它a.prop
將a
a.prop
轉換為一個對象,但並非相同。 因此,JavaScript將其處理如下:
var a = 6;
new Number(a).constructor.prototype.prop = 5;
print(new Number(a).prop);
new Number(a).prop = 4; // assigning prop to an object which is discarded
print(new Number(a).prop); // accessing prop from an object which has no prop
有關更多信息,請閱讀以下答案: https : //stackoverflow.com/a/15705498/783743
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.