因此,我的目标是设置特殊属性的卡。以一种方式,我的前三个console.log将打印false (默认情况下),但在代码之后,它将打印true。我尝试了几种方法(在卡中描述一个将this.special设置为true的方法,然后调用该方法。没有起作用)。而且,仅仅更改card.special也不起作用。谢谢,
function card(name,value,special) {
this.name = name,
this.value = value,
this.special = special
}
var a9 = new card("nine",9,false);
var a10 = new card("Ten",9,false);
var aal = new card("lower",9,false);
console.log(a9.special);
console.log(a10.special);
console.log(aal.special);
//code comes here
console.log(a9.special);
console.log(a10.special);
console.log(aal.special);发布于 2016-12-01 11:54:36
使用原型存储special
function card(name,value,special) {
this.name = name;
this.value = value;
}
card.prototype.special= false;
var a9 = new card("nine",9);
var a10 = new card("Ten",9);
var aal = new card("lower",9);
console.log(a9.special); //false
console.log(a10.special); //false
console.log(aal.special); //false应该注意的是,只要您不修改对象上的special,它就会一直指向prototype中的原始值,但是当您在某个对象上更改它时,就会得到它自己的副本wiz。不再指向prototype.For示例:
假设现在您有一个异常卡,您希望special成为true
aal.special=true;
console.log(aal.special);//true它不会影响其他人,而会得到它自己的独立拷贝
console.log(a9.special); //false
console.log(a10.special); //false
card.prototype.special= true; // make all true
console.log(a9.special); //true
console.log(a10.special); //true发布于 2016-12-01 08:52:46
您可以创建一个原型函数,用于控制台记录变量并更改其值。
card.prototype.logToggleSpecial = function() {
console.log(this.special);
if(!this.special)
this.special = !this.special;
};与调用控制台日志不同,只需调用一个9.logTogglerSpecial()即可。已经试过了,而且成功了。
发布于 2016-12-01 09:05:05
这是你想要的吗?
var counter = 0;
function Card(name, value, special) {
this.name = name,
this.value = value,
this.special = special;
}
defineSpecial(Card.prototype)
function defineSpecial(o) {
var specialValue;
Object.defineProperty(o, 'special', {
get() {
if (counter++ <= 2) {
return false;
}
return specialValue;
},
set(val) {
specialValue = val;
}
});
}
var a9 = new Card("nine",9,true);
var a10 = new Card("Ten",9,true);
var aal = new Card("lower",9,true);
console.log(a9.special);
console.log(a10.special);
console.log(aal.special);
//code comes here
console.log(a9.special);
console.log(a10.special);
console.log(aal.special);
https://stackoverflow.com/questions/40906054
复制相似问题