0

I tried to pass to null an instance of class but in vain. Here avatar2 is not delete, why ? console log

class Avatar{
  constructor(name, weapon = "knife", pv = 100){
    this.name = name;
    this.weapon = weapon;
    this.pv = pv;
  }
  attaqueDefault(target){
    if (target.hasOwnProperty('pv'))
      target.pv -= 20;
  }
  attaqueCombine(target){
    if (target.hasOwnProperty('pv'))
      target.pv -= 35;
  }
  destroy(target){
    target = undefined;
  }
}

var avatar = new Avatar("tchod");
var avatar2 = new Avatar("tchod2", ".44");

avatar.destroy(avatar2);
  • 1
    because the `target` parameter creates a new variable pointing to the instance of the passed class, but any other variable still holds a reference to it. To do what you are trying you would need all variables to point to the same instance, say an object property – pilchard Oct 18 '21 at 22:31
  • You can try using the delete operator: `delete avatar2` instead of calling the .destroy() method with parameter, in this way you can't remove the reference to the object. – F.Igor Oct 18 '21 at 22:34
  • There are few alternatives. Why not just set the pv to 0 in the destroy method? Another way would be to maintain a Map of the Avatars and the destroy method could remove the avatar from the Map. – Paul Rooney Oct 18 '21 at 22:37

1 Answers1

0

try changing avatar to Avatar

Avatar.destroy(avatar2);
somedev
  • 1
  • 5
  • 1
    Hey, welcome to Stack Overflow! Small suggestions like this are best left as comments (particularly if you're not 100% sure) as answers are generally for definitive solutions to a question. But also - you'd use the capital (i.e., the class name) `Avatar`, if `destroy` was a static method, however as you can see it's an instance method, so `avatar.destroy(avatar2);` would be the correct way to call the function. This issue here, is how that function tries to destroy the instance. It only sets the reference passed into the function to undefined, rather than actually changing the instance. – NBTX Oct 18 '21 at 22:48