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
The automatic conversion of primitive data type into its corresponding wrapper class is known as autoboxing, for example, byte to Byte, char to Character, int to Integer, long to Long, float to Float, boolean to Boolean, double to Double, and short to Short.
So a primitive wrapper class is a wrapper class that encapsulates, hides or wraps data types from the eight primitive data types, so that these can be used to create instantiated objects with methods in another class or in other classes.
One major difference from the explanation above is, default values of the primitive types depend on type like int is 0 , char is \u0000 , boolean is false etc but default value for wrapper classes of all types is null since they are objects.
In JavaScript, a primitive (primitive value, primitive data type) is data that is not an object and has no methods or properties. There are 7 primitive data types: string.
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 (e.g. 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, i.e. Boolean objects are immutable.
However, you could add a method to Boolean.prototype to change that if you wanted....
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With