使用JavaScript对象构造函数

时间:2015-02-21 00:56:16

标签: javascript oop javascript-objects

我想验证何时执行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

2 个答案:

答案 0 :(得分:1)

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

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

答案 1 :(得分:0)

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

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

关键是" isAlive" 参数到你的构造函数是一个完全不同的东西," isAlive"构造对象的属性

相关问题