Koppany Koppany - 1 year ago 69
Javascript Question

How to change prototype value which would overwrite objects value? Is it possible?

So my objective is to set the special property of card. In a way that my first three console.log would print false (as default), but after the code it would print true. I tried several ways (describing a method in card to set this.special to true, and called the method afterwhile. Didnt work). Also just changing card.special did not work. Thanks,

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

//code comes here

Answer Source

Use prototype to store 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

It should be noted that as long as you don't modify special on an object it would keep pointing to the original value in prototype but when you change it on some object that one gets its own copy wiz. no longer pointing to the prototype.For example :

suppose now you have an exception card for which you want special as being true


It won't affect others rather it gets it's own independent copy

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
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download