Try avoiding this
and new
keywords when using classes, in my opinion, is a bad idea. The following snippet:
class Offer {
// ...
}const anOffer = new Offer(/* ... */);
is better than what you are proposing.
Even though I like hiding details using closures, there is a little misunderstanding on what private
means: usually private
keyword means class private, not instance private.
In your case every property of the class that has not a getter, cannot be accessed by another instance of the same class. That is not the case of a statically typed language: in Java another instance can access a private member of the same class. This is used, for example, when implementing equals(...)
or hashcode()
functions: equals may need to access private fields of the class.
Finally, in your solution, the object you return is not an instance of Offer, as opposite to using new
keyword on a class.
I understand what you are proposing, but since ES6 introduction, there is no need to do what you suggested. To avoid problems with the this
keyword use classes and arrow functions. E.g.:
class Greetings {constructor(greetingLabel) {
this._greetingLabel = greetingLabel;
}
greetAfterAWhile() {
setTimeout(()=>console.log(this._greetingLabel), 100);
}
}