使用 JavaScript 个对象构造函数

working with JavaScript object constructors

我想验证 属性 值何时执行 var obj = new Object(value); 和何时执行 obj.value = newValue。在我下面采用的方法中,我似乎能够使一个或另一个工作,但不能同时工作。有没有办法让两者在同一个对象声明中工作?

在下面的代码片段中,我只想接收布尔值,所以我说“如果接收到的值不是布尔值,则只需分配 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

View on JSFiddle

第一个不起作用,因为分配给实例化对象的 "isAlive" 属性 只是执行该分配。构造函数中的代码仅在您调用构造函数时运行。

第二个示例中的代码工作正常。问题是您的 setter 只接受布尔值。如果将 "isAlive" 属性 设置为字符串,则 setter 中的代码会将值设置为 true.

关键是构造函数的"isAlive" 参数与"isAlive" [=27完全不同=]构造的对象。

要使两者都正常工作,只需在构造函数中设置 属性,然后像这样定义它:

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?
    }
  });

  this.isAlive = isAlive;
};

JsFiddle