FrontendJavascriptWeb Design

What is factory function and Constructor function in Javascript?

Factory Function in Javascript?

A Factory function is a function that create a object and return it. It is similar to constructor functions.

Factory function is not use this keyword  in the object.

Let take the Example of Factory Function:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
function createCircle(radius){
return {
radius,
draw(){
console.log('Draw a line')
}
}
}
const newCircle = createCircle(5);
console.log(newCircle)
function createCircle(radius){ return { radius, draw(){ console.log('Draw a line') } } } const newCircle = createCircle(5); console.log(newCircle)
function createCircle(radius){
    return {
        radius,
        draw(){
             console.log('Draw a line')
        }
    }

}

const newCircle =  createCircle(5);
console.log(newCircle)

 

What is constructor Function?

Constructor function is a special function which initialize a object when it called.

when we call a constructor, we should use new keyword.

It is a create new empty object and we also do not need to return word in the function body.

May be you don’t  know that, A function is a object.

In Constructor function, this keyword refer to existing object.

Also use first word capital in function name like:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
function CreateCircle(){
}
function CreateCircle(){ }
function CreateCircle(){
}

let’s take the Example of Constructor Function:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
function CreateCircle(radius){
this.radius = radius;
this.draw = function(){
console.log(`Call a Draw Function with ${radius}`);
}
}
const createcircle = new CreateCircle(5);
console.log(createcircle.draw())
function CreateCircle(radius){ this.radius = radius; this.draw = function(){ console.log(`Call a Draw Function with ${radius}`); } } const createcircle = new CreateCircle(5); console.log(createcircle.draw())
function CreateCircle(radius){
    this.radius = radius;
    this.draw = function(){
      console.log(`Call a Draw Function with ${radius}`);
    }
}
const createcircle = new CreateCircle(5);
console.log(createcircle.draw())

when we are calling a constructor 3 things are happening:

  • First create a new empty object
  • using this keywords for property
  • The new object is then returned as the return value of the constructor.

Most of the student confuse with this keyword. I will also explain in details about it.

Which one do you use factory function or constructor function, please us know by giving comments.

 

Related Articles

Leave a Reply

Your email address will not be published. Required fields are marked *

Back to top button