ES6 Classes

Greeting

// Class
class Person{

    // Constructor
    constructor(firstName, lastName, dob){
        this.firstName = firstName;
        this.lastName = lastName;
        this.birthday = new Date(dob);
    }

    // Greeting method
    greeting(){
        return `Hello there ${this.firstName} ${this.lastName}`;
    }

    // Calculate Age
    calculateAge(){
        const diff = Date.now() - this.birthday.getTime();
        const ageDate = new Date(diff);
        return Math.abs(ageDate.getUTCFullYear() - 1970);
    }

    getsMarried(newLastName){
        this.lastName = newLastName;
    }

    // Static method
    static addNumbers(x, y){
        return x + y;
    }

}

// Create an object from the class
const mary = new Person('Mary', 'Williams', '1980-12-09');

// Update name with getsMarried function
mary.getsMarried('Thomson');

console.log(mary);

console.log(Person.addNumbers(2,2))
Was this page helpful?

Reader Interactions

Leave a Reply

Your email address will not be published. Required fields are marked *