DEV Community

Cover image for Class in ES6 vs Class in Typescript
Tuan Huynh
Tuan Huynh

Posted on

Class in ES6 vs Class in Typescript

Class in pre-ES6

var employee = {
    name: null,
    age: null,

    setName: function (name) {
        this.name = name;
    },

    getName: function () {
        return this.name;
    },

    setAge: function (age) {
        this.age = age;
    },

    getAge: function () {
        return this.age;
    }
};
Enter fullscreen mode Exit fullscreen mode

Class in ES6

class Employee {
    constructor (name, age) {
        this.name = name;
        this.age = age;
    }

    setName (name) {
        this.name = name;
    }

    getName () {
        return this.name;
    }

    setAge (age) {
        this.age = age;
    }

    getAge () {
        return this.age;
    }
};

class MaleEmployee extends Employee {
    constructor (name,age,wifeName) {
        super(name,age);
        this.wifeName = wifeName;
    }

    setWifeName (wifeName) {
        this.setWifeName;
    }

    getWifeName () {
        return this.wifeName;
    }

    classClassName () {
        return super.getClassName();
    }
}

var employee = new MaleEmployee();
console.log(employee.classClassName());
//Result: Class Employee
Enter fullscreen mode Exit fullscreen mode

Class in Typescript

class Person {
    protected name: string;
    constructor(name: string) { this.name = name; }
}

class Employee extends Person {
    private department: string;

    constructor(name: string, department: string) {
        super(name);
        this.department = department;
    }

    public getElevatorPitch() {
        return `Hello, my name is ${this.name} and I work in ${this.department}.`;
    }
}

let howard = new Employee("Howard", "Sales");
console.log(howard.getElevatorPitch());
console.log(howard.name); // error
Enter fullscreen mode Exit fullscreen mode

Top comments (0)