javascript - 使用 JavaScript 对象构造函数

标签 javascript oop javascript-objects

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

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

最佳答案

要使两者都工作,只需在定义属性后在构造函数中设置属性,如下所示:

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

关于javascript - 使用 JavaScript 对象构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28640769/

相关文章:

javascript - jQuery 通过识别属性确定所选元素的 CSS 是否具有某些属性

javascript - 动态更新 Grunt 配置字段

java - 接口(interface)内的静态工厂方法

javascript - 返回空对象的箭头函数然后返回一个函数?

实现删除链表中的节点时,Javascript改变对象的内存

javascript - 搜索对象数组并在值与字符串或子字符串匹配时返回整个对象

javascript - 如何通过Javascript中另一个类的实例访问另一个类中的方法

javascript - 仅将类添加到一个 div

python - isinstance 在 python 中如何为子类工作?

php - 我正在使用“添加查询”创建 PHP OOP 连接