Constructor functions in JavaScript

A constructor function is a function whose instance is created using the 'new' keyword.

Constructor functions in JavaScript can be declared using classes or by using JavaScript functions 'with few tweaks'

How to create a constructor in JavaScript

For JavaScript functions construction declaration can be made as follows;

const greeting = function(name) {
    this.name = name
}

greeting.morning = function() {
    const name = this.name
    return `morning ${name}`
}

In the code bove declared a function greeting with a parameter named 'name'

I further created a method named morning it returns a template greeting message

Once the program gets run on a JavaScript engine the expected output is;

morning + 'name provided'

For instance;

const greet = new greeting('John')

greet.morning()
// returns 'morning John'

Similar to using functions as constructors you can as well declare using classes;

const greeting = class {
    constructor(name) {
        this.name = name
    }
   
    morning() {
    const name = this.name
    return `morning ${name}`
    }
}

const greet = new greeting('Joe')

greet.morning()
// returns 'morning Joe'

Comments

Popular posts from this blog

Open-graph meta data tags introdution

What is 'this.' keyword in JavaScript

How to create zip archives in nodejs

what is 'array.includes' function in JavaScript

How to build a twitter retweet bot using JavaScript