Skip to content

Instantly share code, notes, and snippets.

@ivankisyov
Last active December 25, 2018 16:06
Show Gist options
  • Save ivankisyov/fd24b3e2b99eb94471db0ec7294385fb to your computer and use it in GitHub Desktop.
Save ivankisyov/fd24b3e2b99eb94471db0ec7294385fb to your computer and use it in GitHub Desktop.
Constructor Functions in JS

Constructor Functions in JS

If you have several objects that share the same implementation, you can use a constructor function to create them.

Any function can be a constructor function as long as it is invoked using the new keyword

function createSillyExample() {}

const objectCreatedFromSillyExample = new createSillyExample();
// result: {}

"Classes" in JS

class Human {
  constructor(name) {
    this.name = name;
  }
  
  getName() {
    return this.name;
  }
}

Here's what's happening here:

  • A new variable Human is created and it's assigned to the constructor function in the "class" from above;
  • getName is a property, which is a method on the prototype of the constructor function;

You are not forced to set constructor method in the class. If not provided, JS engine will provide the following:

  • constructor() {}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment