DEV Community

Discussion on: HOW TO CREATE OBJECTS IN JAVASCRIPT

Collapse
 
thepeoplesbourgeois profile image
Josh • Edited

Why not sanitize the object keys in the factory function? And the arguments in the class-like variation, for that matter? There's not any apparent reason the underscores need to be there.

function Person(name, age) {
  this.name = name;
  this.age = age;
  this.Greeting = function() {
    // ...
  }
} 

function personFF(name, age) {
  return {
    name, 
    age,
    // no reason the factory version can't have  the Greeting function, either
    Greeting() {
      // ...
    }
  };
}
Collapse
 
salaheddin12 profile image
Salah Eddine Ait Balkacm

This is a constructor that creates an instance of a Person

function Person(name, age) {
  this.name = name;
  this.age = age;
  this.Greeting = function() {
    // ...
  }
} 

And this is a factory fuction that creates an object of type personFF by returning an object with the properties geven as parameters

function personFF(name, age) { //here age and name can be named anything.
//this (name_ and age_) is just a naming convention I used :)
  return 
  //this returns an object using the object literal.
  //so the object that we return can have as many properties and methods depending on our //needs.
  {
    name, 
    age,
    //we can add methods and properties here
  };
}