0
const startGame = {
 time : 0,
 start : function(){

 }
 next : function(){
 
 }

 end : function(){

 }
}


const anotherGame = { //want to inherit from startGame
 startAnother : function(){} //want to inherit from startGame.start
}

Given an object like this, I would like to inherit from it and give it a new property. For example, anotherGame extends startGame and takes all other properties, but I want to write additional code in addition to the properties of start function of startGame except for anotherStart function. What should I do ?

1
  • 1
    It's not really clear what you are trying to do here. Inheritance is something that happens to classes (and constructor functions) rather than on plain objects or regular functions. It would probably help if you provided a simple example of what you were trying to acheive instead of a collection of completely empty functions and a very vague description of how you want to build on it. Commented Mar 28, 2022 at 9:10

1 Answer 1

2

Under the hood, ES6 classes use prototype to achieve inheritance:

const startGame = {
  time: 0,
  start: function () {
    console.log("works", this.time);
  },
  next: function () {},
  end: function () {},
};

const anotherGame = {
  //want to inherit from startGame
  startAnother: function () {
    this.start();
  }, //want to inherit from startGame.start
};

// Magic happens here
Object.setPrototypeOf(anotherGame, startGame);

anotherGame.startAnother();

Using ES6 classes:

class StartGame {
  time = 0;

  start() {
    console.log("works", this.time);
  }
  next() {}
  end() {}
}

class AnotherGame extends StartGame {
  startAnother() {
    this.start();
  }
}

const anotherGame = new AnotherGame();

anotherGame.startAnother();

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.