Day 6: ES2015

Object Enhencement

In ES5 if you want to make an object with some fields, you do this

function getPerson() {
    let name = 'John';
    let age = 25;

    return {
        name: name,
        age: age
    };
}

but in ES6 if your field name is the same as the variable and get rid of the value.

function getPerson() {
    let name = 'John';
    let age = 25;

    return {
        name, 
        age, 
        greet() {
            return `Hello ${this.name}`
        }
    };
}

alert(getPerson().greet());

Much cleaner.

Object Destructuring

let person = {
    name: 'John',
    age: 32,
    job: 'piper',
    place: 'singapore'
};

let {name, age, job, place} = person;
alert(place);

Without object destructuring you do something like this:

function getData(person) {
    var name = person.name;
    var age = person.age;

    console.log(name, age);
}

getData(person);

But now you can do this:

function getData({name, age}) {
    console.log(name, age);
}
getData(person);

Class

The old way:

function User(username, email) {
    this.username = username;
    this.email = email;
}
User.prototype.changeEmail = function(newEmail) {
    this.email = newEmail;
};

New way:

class User {
    constructor(username, email) {
        this.username = username;
        this.email = email;
    }

    static register(...args) {
        return new User(...args);
    }

    get capName() {
        let name = this.username;
        name = name.toUpperCase();
        return name;
    }

    changeEmail(newEmail) {
        this.email = newEmail;
    }
}

So you have static methods as well, so that you can do User.register(name, mail).

Modules

Modules are basically individual javascript files that you can import from other files, just make sure you export the module first to expose it to other files.
e.g. you have this TaskCollection.js

export default class TaskCollection {
    constructor(tasks = []) {
        this.tasks = tasks;
    }

    dump() {
        console.log(this.tasks);
    }
}

You want to use it from your main.js

import TaskCollection from './TaskCollection';

let tl = new TaskCollection([
    'chekc 1',
    'chekc 2',
    'check 3'
]);

tl.dump();

But in order for this to work, you need to use something called module bundler like rollup, webpack, etc. Then you need a transpiler to convert it to ES5 friendly javascript. WTF?
I’m so done with this javascript world.

Leave a Reply

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