Discussion

Ask HN: What are good patterns for holding state?

It's common practice to use classes when needing to hold state. However, I'm wondering if it's the best approach when you don't need all the baggage OOP comes with like inheritance, etc...

Here is an example of how I would go about it without classes :

function makePlayer() {

   const data = {
      x: 100,
      y: 100,
      health: 300,
      speed: 200
   }

   const methods = {
      setHealth(value){
        data.health = value
      },
      // etc...
   }

   return {...data, ...methods}
}

Do you think this is a good approach? If not, why?

EDIT: The question is meant to be general and not specific to a given framework or library. For something like React you use what is given by the library. There isn't much room for choice here.

7 points JSLegendDev 2 years ago 13 comments

Discussion

Live from the official Hacker News API

A modern reader for Hacker News · SvelteKit + Skeleton