Constructors that produce frozen instances?
# David Bruant (12 years ago)
Le 08/06/2013 20:22, Axel Rauschmayer a écrit :
It's difficult to do that if you want your constructors to remain subtypable. Is the following the best we can do? A constructor can only freeze if it is the first constructor that is invoked.
function Point(x, y) { this.x = x; this.y = y; if (this.constructor === Point) { Object.freeze(this); } } function ColorPoint(x, y, color) { Point.call(this, x, y);
Super-ugly solution: warp 'this' in a proxy with a shadow (freezable) target and forward all non-freezing operations to 'this'.
this.color = color; if (this.constructor === ColorPoint) { Object.freeze(this); } } ColorPoint.prototype = Object.create(Point); ColorPoint.prototype.constructor = ColorPoint;
(More detailed write-up: www.2ality.com/2013/06/freezing-instances.html )
Maybe classes and the @@construct separation (and convention) can help?
It’s difficult to do that if you want your constructors to remain subtypable. Is the following the best we can do? A constructor can only freeze if it is the first constructor that is invoked.
(More detailed write-up: www.2ality.com/2013/06/freezing-instances.html )