Javascript - Class Class Methods

Introduction

Prior to ES6 you needed the Object.defineProperty() to make a method non-enumerable.

In ES6 all methods of a class are non-enumerable.

These methods are attached to the prototype, which enables the method to be shared by all instances of the class.

The syntax for defining methods of a class in ES6 is similar to the object literal method shorthand.

You do not need the function keyword to create functions:

Demo

class Bus { 
        constructor(model, capacity) { 
                this.model = model; // w ww.  j ava2  s.  co m
                this.capacity = capacity; 
        } 
        getData() { 
                console.log(`You're traveling a ${this.model} bus`); 
                console.log(`This plane can travel with ${this.capacity} passengers`); 
        } 
} 

const jet = new Bus("Jet", 60); 

jet.getData(); 
console.log(jet.hasOwnProperty("getData"));                     // false 
console.log(jet.__proto__.hasOwnProperty("getData"));           // true

Result

The above example creates a class Bus which accepts two value:model and capacity.

This getData() method gets automatically added to the prototype.

The ES5 way to re-create the above example would be:

function Bus(model, capacity) { 
        this.model = model; 
        this.capacity = capacity; 
} 

Bus.prototype.getData = function() { 
        console.log("You're traveling a " + this.model + " bus"); 
        console.log("This plane can travel with " + this.capacity + " passengers"); 
} 

var jet = new Bus("Jet", 60); 

jet.getData();