0

I'm learning JavaScript for backend and i'm struggling to understand what is the safest object creation method. Factory Functions? Eventmittler3? Class with Object.create? Or its depend on where i will use? If so, can you please explain how can i aarchieve this 'finding best method' what should i look for?

function person(name, age){
    return {name, age}
}

is something like that safe to use creation users in an production-ready app?

Kerem Z
  • 13
  • 5
  • `var obj = {name: 'Bob', age: 22}` is safe, we maybe need more context on what problem your wanting to solve. If it's safe code, then a popular choice is to use Typescript to create your Javascript. – Keith Jul 14 '21 at 20:29
  • 1
    usually people would do something like `class Person { constructor(name, age) { this.name = name; this.age = age; } }` [Classes on MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes) – Samathingamajig Jul 14 '21 at 20:33
  • @Samathingamajig They would only use `class`es if they needed prototype methods on the objects – Bergi Jul 14 '21 at 20:37
  • What do you mean by "safest"? – Bergi Jul 14 '21 at 20:38
  • It's really unclear how you would use EventEmitter3 to create objects. – Bergi Jul 14 '21 at 20:39
  • Classes and `Object.create` are separate object creation approaches, not used together. – Bergi Jul 14 '21 at 20:39
  • @Bergi not necessarily. `instanceof` and other prototypal inheritance tests, easier typedefs with TypeScript, etc. are other reasons to use `class`es instead of raw objects – Samathingamajig Jul 14 '21 at 20:48
  • @Bergi i mean with safest for use in an CRUD App not an API and i had read that 'new' Keyword is not good to use, but i didn't actually understood why. – Kerem Z Jul 15 '21 at 19:47
  • @Bergi here is an article: https://medium.com/javascript-scene/3-different-kinds-of-prototypal-inheritance-es6-edition-32d777fa16c9 – Kerem Z Jul 15 '21 at 19:47
  • @KeremZ `EventEmitter3` is just an example for usage of a *mixin* in that article. `EventEmitter3` is not a method to create objects. – Bergi Jul 15 '21 at 23:12
  • @KeremZ All the styles in that article are safe for use, and are used in production code around the world. They just have different tradeoffs (e.g. memory efficiency, simple syntax, etc), but that's for you to choose. "*I had read that 'new' Keyword is not good to use*" - [that's rubbish](https://stackoverflow.com/q/383402/1048572). Whoever is telling you that, without a proper explanation of why they think so and how this is just their personal preference, is spreading FUD. – Bergi Jul 15 '21 at 23:15
  • @Bergi i couldn't find where i had read that but okay. For now i may choose the simple syntax. If any performance improvements needed, better i learn them in that case. – Kerem Z Jul 16 '21 at 06:57

0 Answers0