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) { = name

greeting.morning = function() {
    const 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')

// returns 'morning John'

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

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

const greet = new greeting('Joe')

// returns 'morning Joe'


Popular posts from this blog

How to set content disposition header for nginx server to force content download

Animated daylight on HTML5 Canvas

How to make a static http server in nodejs using express

JS13K Preparation

Adding Gameover and introduction screen on HTML Canvas