Use class statement to create class - Node.js Object

Node.js examples for Object:Class Definition

Description

Use class statement to create class

Demo Code


'use strict';/*from w  ww  .j  a  va2  s  .  c o  m*/

class Animal {
    constructor(type, sound) {
        this.type = type;
        this.sound = sound;
    }

    makeNoise() {
        return 'The ' + this.type + ' goes ' + this.sound;
    }
}

var lion = new Animal('lion', 'roar');
console.log(lion.makeNoise());

// ES5

var ES5Animal = function(type, sound) {
    this.type = type;
    this.sound = sound;
};

ES5Animal.prototype.makeNoise = function() {
    return 'The ' + this.type + ' goes ' + this.sound;
};

var cat = new ES5Animal('cat', 'meow');
console.log(cat.makeNoise());

Related Tutorials