I'd like to validate property values for when do var obj = new Object(value); and when i do obj.value = newValue. In the methods I've employed below I seem to be able to get one or the other to work, but not both. Is there a way to get both to work in the same object declaration?
In the snippet below I'd like to receive Boolean values only, so I've said "if value received is not Boolean then just assign 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