Inheritance And Classes

See for a good quick guide https://strongloop.com/strongblog/an-introduction-to-javascript-es6-classes/

ES5

function Programmer(name, programmingLanguage) {
    this.name = name;
    this.programmingLanguage = programmingLanguage;
}
 
Programmer.prototype = Object.create(Person.prototype);
Programmer.prototype.constructor = Programmer;
 
Programmer.prototype.writeCode = function() {
    console.log(this.name + ' is coding in ' + this.programmingLanguage + '.');
}
 
var cory = new Programmer('Cory', 'JavaScript');
cory.walk();        // Outputs 'Cory is walking.'
cory.writeCode();   // Outputs 'Cory is coding in JavaScript.'

ES6

class Programmer extends Person { 
    constructor(name, programmingLanguage) {
        super(name);
        this.programmingLanguage = programmingLanguage;
    }
 
    writeCode() {
        console.log(this._name + ' is coding in ' + this._programmingLanguage + '.');
    }
}
 
let cory = new Programmer('Cory', 'JavaScript');
cory.walk();        // Outputs 'Cory is walking.'
cory.writeCode();   // Outputs 'Cory is coding in JavaScript.'
class Person {
    constructor(name) {
        this._name = name;
    }
 
    get name() {
        return this._name;
    }
 
    set name(newName) {
        this._name = newName;
    }
 
    walk() {
        console.log(this._name + ' is walking.');
    }
}
 
class Programmer extends Person { 
    constructor(name, programmingLanguage) {
        super(name);
        this._programmingLanguage = programmingLanguage;
    }
 
    get programmingLanguage() {
        return this._programmingLanguage;
    }
 
    set programmingLanguage(newprogrammingLanguage) {
        this._programmingLanguage = newprogrammingLanguage;
    }
 
    writeCode() {
        console.log(this._name + ' is coding in ' + this._programmingLanguage + '.');
    }
}
 
let bob = new Person('Bob');
bob.walk();
 
let cory = new Programmer('Cory', 'JavaScript');
cory.walk();
cory.writeCode();
console.log(cory.name);
Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License