Friday, July 20, 2018

Javascript 6: a first look

OMG, modern javascript has added so many things (ok, may not work on some oldie browser). Check this out http://es6-features.org

Now it even has object oriented features, modules and stuff. Even has some interesting string manipulation, and gosh much more.

Tweaked a bit of samples to illustrate some, put in a <script> tag, and watch console.


// String manipulation, and extend your lines with backquote

var customer = { name: "John" }
var item = { howmany: 7, product: "Candy Bar", unitprice: 5 }

var message = `Hello ${customer.name},
want to buy ${item.howmany} ${item.product} for
a total of ${item.howmany * item.unitprice} dollars?`

console.log("message: "+message)

// ------------------
// OOP for javascript

class Shape {
    constructor (id, x, y) {
        this.id = id
        this.move(x, y)
    }
    move (x, y) {
        this.x = x
        this.y = y
        console.log("Shape: move to ("+x+","+y+")");
    }
}

class Rectangle extends Shape {
    constructor (id, x, y, width, height) {
        console.log("Rectangle ctor");
        super(id, x, y)
        this.width  = width
        this.height = height
    }
}
class Circle extends Shape {
    constructor (id, x, y, radius) {
        console.log("Circle ctor");
        super(id, x, y)
        this.radius = radius
    }
}

var c = new Circle(1,100,100,5);
var r = new Rectangle(2,10,30,50,50);

No comments: