简体   繁体   中英

Can not modify properties added to Number.prototype

Could somebody please explain this behavior in JavaScript?

var a = 6;
a.constructor.prototype.prop = 5;
print(a.prop);
a.prop = 4;
print(a.prop);

Then I run it in ideone:

5
5

I understand that a itself is a number , but its prorotype is object . But why such discrepancy exist? Surely this can be the source of multiple coding errors. Is this considered a "evil part" of JavaScript?

The problem is that a is a primitive value. 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. 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/

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.

The same is true for all primitives - booleans, numbers and strings in JavaScript. This is the reason print(a.prop) always prints 5 - a is a primitive, not an object.

When you try to access a.prop it coerces a into an object but not the same object every time. Hence JavaScript treats it as follows:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM