Home > database >  How do I make the child object not inherit a method or property from the parent object?
How do I make the child object not inherit a method or property from the parent object?

Time:10-22

I'm creating a child object using class, but I don't want it to inherit some properties and methods from the parent object.

I want to know if there is any way to do this.

my code:

 class Player {
  #name;
  #marking;
  #score;
  constructor(){
   this.#name = undefined;
   this.#marking = undefined;
   this.#score = {wins:0,defeats:0};
  }
  action(){...}
  
  getName(){...}
  setName(){...}
  ...
 }

 class AIPlayer extends Player{
  constructor(){
   super();
   this.#name = "AI-0.1.2";
   
  }
  action(){...}

  //I don't want AIPlayer to inherit setName() or #score 
  
 }
  
 const p1 = new Player();
 p1.setName("Mr.Banana);
 console.log(p1.getName()); //-> Mr.Banana

 const AIP0 = new AIPlayer();
 AIP0.setName("stupid computer"); //->error
 console.log(AIP0.getName()); //-> AI-0.1.2

CodePudding user response:

Change setname to a private method. #setname(){}

CodePudding user response:

Just overload method:

setName(name) {
  throw "name can not be set"
}
  • Related