[英]Can not modify properties added to Number.prototype
Could somebody please explain this behavior in JavaScript? 有人可以用JavaScript解释这种行为吗?
var a = 6;
a.constructor.prototype.prop = 5;
print(a.prop);
a.prop = 4;
print(a.prop);
Then I run it in ideone: 然后我在ideone中运行它:
5
5
I understand that a
itself is a number
, but its prorotype is object
. 我知道
a
本身就是一个number
,但是它的原型是object
。 But why such discrepancy exist? 但是为什么存在这种差异呢? Surely this can be the source of multiple coding errors.
当然,这可能是多个编码错误的根源。 Is this considered a "evil part" of JavaScript?
这是否被视为JavaScript的“邪恶部分”?
The problem is that a
is a primitive value. 问题在于
a
是原始值。 Not an object. 不是对象 You can only assign properties to objects.
您只能将属性分配给对象。 Not primitive values.
不是原始值。
When you try to assign a property to a primitive value, JavaScript immediately coerces it to an object. 当您尝试将属性分配给原始值时,JavaScript立即将其强制为一个对象。 For example:
例如:
var x = true; // x is primitive
x.y = false; // x is coerced to an object
alert(x.y); // y is undefined
See the demo here: http://jsfiddle.net/UtYkA/ 在此处查看演示: http : //jsfiddle.net/UtYkA/
What's happening in the second line is: 第二行中发生的是:
new Boolean(x).y = false; // x is not the same as new Boolean(x)
Because x
is coerced into an object and the property y
is added to this object no property has been added to the x
itself. 因为
x
被强制到一个对象中,并且属性y
被添加到该对象,所以没有将属性添加到x
本身。
The same is true for all primitives - booleans, numbers and strings in JavaScript. 对于所有原语(JavaScript中的布尔值,数字和字符串)都是如此。 This is the reason
print(a.prop)
always prints 5
- a
is a primitive, not an object. 这是原因
print(a.prop)
始终打印5
- a
是原始的,而不是一个对象。
When you try to access a.prop
it coerces a
into an object but not the same object every time. 当您尝试访问
a.prop
它a.prop
将a
a.prop
转换为一个对象,但并非相同。 Hence JavaScript treats it as follows: 因此,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
For more information read the following answer: https://stackoverflow.com/a/15705498/783743 有关更多信息,请阅读以下答案: https : //stackoverflow.com/a/15705498/783743
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.