0

I'm creating a simple turn based multiplayer game. I will have some "unit" objects I want pass back and forth. I wanted to define the definition of the object only once. In C++ I would use a header file, and in Java I could implement them them, but in Javascript I don't know how I could achieve this.

I could simply define everything twice, but I have a feeling this might come up again in my future at some point, and I rather learn to deal with it properly now. I'm using Nodejs and Javascript.

As a note, I thinking I could just do a simple HTML but I was having a hard time figuring out how to do the same thing on the server.js, and I'm not sure if this is even how I should be handling this.

1
  • 1
    Javascript is dynamic, creating a "defintition" isn't something that can be done well since everything can be changed so an interface or a definition is meaningless. It's impossible to enforce an object structure unless you use something like TypeScript. Commented May 16, 2016 at 0:37

2 Answers 2

1

I don´t know if I understand your question correctly. But I would just define the unit Object in a file and export it from there. You could use Object.freeze() or Object.seal() (depending on your use case), which will prevent the Object from being modified/props from being added. Also if you want to initialize it with dynamic values, you would define a function returning the sealed/frozen Object:

const unit = Object.seal({
  name: 'hello'
  ....
});

export default unit;
Sign up to request clarification or add additional context in comments.

Comments

1

Create a module with your logic and require it, both in the front end and in the server. This way you will have your logic defined in a single place, reused wherever you need it.

Have a look at http://browserify.org/ for the front end.

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.