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;
}
}
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!
LikeLike
Hi, thank you for your feedback.
What make the date attribute immutable is :
get date() {
return new Date(this._date.getTime());
}
So, always you are returning a new instance of this object.
LikeLike