Create objects using class, constructor function, Factory function in JavaScript

·

2 min read

in javaScript, you can instantiate an object using three different method

Create objects using class

class Employee {

    constructor(name,age,sex)
    {
        this.name = name;
        this.age  = age;
        this.sex = sex;
    }

}

var employe = new Employee( "John Doe", "25", "Male" )

The main difference between the constructor function, class , and Factory Function is that the construct function , class must use a new Keyword to instance an object but the factory function you can instantiate an object without new keyword

Create Construct Function

the names have to be capitalized and it's not a normal function

function ConstructorFunction (name,age,sex)
{
        this.name = name;
        this.age  = age;
        this.sex  = sex;
}

var employ1 =  ConstructorFunction("John Doe","25","Male"); // this return undefined
var employ2 =  new ConstructorFunction("John Doe","25","Male"); // this return an object

Factory Function

notice that we don't need new keyword

function FactoryFunction(name,age,sex)
{
    return obj = {
        name : name,
        age  : age,
        sex  : sex
    }
}
    employ1 = FactoryFunction("Jhon Doe","25","Male")