Javascript - Class Class Methods


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:


class Bus { 
        constructor(model, capacity) { 
                this.model = model; /*from   w  w w .  ja va2 s. c  o  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); 

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


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);