[JS] – Example of a immutable class in Javascript

class Sell {

    constructor(date, quantity, price) {

        this._date = new Date(date.getTime()); // new instance  
        this._quantity = quantity;
        this._price = price;
        Object.freeze(this);
    }

    get totalPrice() {
        return this._quantity * this._price;
    }

    get date() {
        return new Date(this._date.getTime());
    }

    get quantity() {
        return this._quantity;
    }

    get price() {
        return this._price;
    }
}

2 Comments

  1. Hi Camila,

    Nice post! 👍

    I’d like to suggest that the instances of the class are maybe 99.9% immutable, rather than 100%. Here’s an example of an interactive node shell where I create an instance of Sell called ‘s’, and modify the date property:

    “`
    > const s = new Sell(new Date(), 10, 20);
    undefined
    > s
    Sell {
    _date: Sat Nov 26 2016 00:50:06 GMT+0000 (GMT),
    _quantity: 10,
    _price: 20 }
    > s._date.setDate(-1)
    1477785006057
    > s
    Sell {
    _date: Sun Oct 30 2016 00:50:06 GMT+0100 (IST),
    _quantity: 10,
    _price: 20 }
    > s.date
    Sun Oct 30 2016 00:50:06 GMT+0100 (IST)
    “`

    I’ve tried a couple of other ways to make the date immutable, but I haven’t figured out any, while there’s a exposed property that’s an object. In this particular case, one option could be to just construct `this._date` with the value of `date.getTime()`, then modify the getter to `return new Date(this._date);`. Of course that’s probably not a very scalable solution that will work for all object-based properties in a class. I’d love to hear your thoughts on other possibilities, if you can think of any!

    Like

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s