When creating a new object with var obj = new Object(value);
and assigning property values with obj.value = newValue
, I encountered an issue where only one of these actions would work at a time. Is there a way to make both work within the same object declaration?
In the code snippet below, I aim to only receive Boolean values. If a non-Boolean value is provided, I want to default to true
.
/*
* why does this work on instantiation but not on property assignment?
*
*/
var robot = function(isAlive) {
this.isAlive = (typeof isAlive === 'boolean') ? isAlive : true; // why does this work on instantiation but not on property assignment?
};
bot4 = new robot(true);
bot5 = new robot("random string");
bot4.isAlive = "random string";
console.log("bot4: " + bot4.isAlive); // -> random string
console.log("bot5: " + bot5.isAlive); // -> true
/*
* why does this work on property assignment but not on instantiation?
*
*/
var android = function(isAlive) {
Object.defineProperty(this, "isAlive", {
get: function() {
return isAlive;
},
set: function(value) {
isAlive = (typeof value === 'boolean') ? value : true; // why does this work on property assignment but not on instantiation?
}
});
};
droid1 = new android(true);
droid2 = new android("random string");
droid1.isAlive = "random string"; // note the string assignment failed and is assigned the default value of true
console.log("droid1: " + droid1.isAlive); // -> true
droid1.isAlive = false; // passed since this is boolean
console.log("droid1: " + droid1.isAlive); // -> false
console.log("droid2: " + droid2.isAlive); // -> random string