简体   繁体   中英

Best way to create a 3 state object in js

How do you create a 3 state object in javascript? Let's say we want to make the game "Snake". There you have a grid of fields where the snake is able to move on. Every field is an object. The object should somehow have the properties "is it a field where the snake is on", "is it a field where a fruit is on" and "is it none of both". Should this be done with a string-property ({state: "fruit"/"snake"/"grass"}) or two boolean-properties ({isSnake: true/false, isFruit: true/false}) .

Which option should I use or is there a better option?

And a follow-up-question: Should I use getters and setters here or is this sufficient?

field.isSnake = true;

and in general, when should you use getters and setters?

Try flag:

const TypeFlags = {
  FRUIT: 1,
  SNAKE: 2,
  GRASS: 4,
};

const field = {
  flag: 1,
};

console.log(
  (field.flag & TypeFlags.FRUIT) !== 0, // fruit
  (field.flag & TypeFlags.SNAKE) !== 0, // snake
  (field.flag & TypeFlags.GRASS) !== 0 // grass
);

Having two booleans, isSnake and isFruit is dangerous, as it can represent four states , but only three are valid. A snake can't be a fruit, but your code allows it to be one. Wether you take strings, numbers or Symbols to represent three states is personal preference.

您的两个答案都取决于您所遵循的编程范例,深入学习编程范例,希望您会得到答案。作为一个初学者,我想您正在使用“面向对象的编程”范例,那么您必须使用Getter和设置器,是的标志,例如“ isSanke”是比使用字符串更清洁的方式

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM