简体   繁体   中英

Change value of a wrapped primitive data type

var test = new Boolean(0)
test.prop = "OK!"

Can you change the value of test to true ?

but test.prop should still be "OK!"

in other words, test should be the same object

Built-in object wrappers (created with the Boolean , Number , String and Date constuctors) store the primitive wrapped value in an internal property named [[PrimitiveValue]] , which cannot be changed, but...

You can override the valueOf method of your test object:

var test = new Boolean(0);
test.prop = "OK!"
// override valueOf:
test.valueOf = function () { return true; };

if (test == true) { // using the equals operator explicitly for type conversion
  alert(test.prop); //"OK!"
}

It will work since the valueOf method is used internally by the type-conversion mechanisms triggered by the equals operator.

When one of the operands is a Boolean value, both are converted at the end to Number.

If we don't use the equals operator (eg if (test) { ... } ), since test is an object, when converted directly to Boolean, it will always yield true .

Any object converted to Boolean will produce the true value, the only values that can produce a false result, are the "falsey" values ( null , undefined , 0 , NaN , an empty string, and of course the false value), anything else will produce true .

More info:

No.

var test = new Boolean(0);

creates a new Object and puts a reference to it in 'test'

test.prop = 'ss'

dynamically puts a new property on the object (meta-programming FTW!)

test = true;

assigns test to a boolean primitive type. The reference to the Boolean object is lost.

Finally, the Boolean object does not appear to have any methods to toggle or reassign its value, ie Boolean objects are immutable.

However, you could add a method to Boolean.prototype to change that if you wanted....

The object wrappers create an immutable reference type in JS. Since in JS the primitive data types are immutable, their references should also be immutable. It might be useful for some rare cases but most probably will fail to do what you want. For instance, if you need to alter the source primitive value and watch the references to follow it, you can't use the Object constructor to achieve the desired effect. Then your best bet would be to avoid the Object constructor and use a proper object literal to harbor your primitive value under a property as follows;

 var pv = "test", pvr = {0: pv}, arr = new Array(5).fill().map(_ => pvr); console.log(JSON.stringify(arr)); pvr[0] = "Hello"; console.log(JSON.stringify(arr)); 

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