我想验证何时执行 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
最佳答案
要使两者都工作,只需在定义属性后在构造函数中设置属性,如下所示:
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;
};
关于javascript - 使用 JavaScript 对象构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28640769/