DEV Community

Randy Rivera
Randy Rivera

Posted on

Use class Syntax to Define a Constructor Function

  • ES6 provides a new syntax to create objects, using the class keyword. It should be noted that the class syntax is just syntax, and not a full-fledged class-based implementation of an object-oriented paradigm, unlike in languages such as Java, Python, Ruby, etc.
  • In ES5, we usually define a constructor function and use the new keyword to instantiate an object.
var Vegetable = function(name){
  this.name = name;
}
var carrot = new Vegetable('carrot');
Enter fullscreen mode Exit fullscreen mode
  • The class syntax simply replaces the constructor function creation.
class Vegetable {
  constructor(name) {
    this.name = name;
  }
}

const carrot = new Vegetable('carrot');
console.log(carrot.name); // Should display 'carrot'
Enter fullscreen mode Exit fullscreen mode

It should also be noted that the class keyword declares a new function, to which a constructor is added. This constructor is invoked when new is called to create a new object.

  • Note: UpperCamelCase should be used by convention for ES6 class names, as in SpaceShuttle used above.

Top comments (0)