Constructors that produce frozen instances?
# David Bruant (13 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 )
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); this.color = color; if (this.constructor === ColorPoint) { Object.freeze(this); } } ColorPoint.prototype = Object.create(Point); ColorPoint.prototype.constructor = ColorPoint; (More detailed write-up: http://www.2ality.com/2013/06/freezing-instances.html ) -- Dr. Axel Rauschmayer axel at rauschma.de home: rauschma.de twitter: twitter.com/rauschma blog: 2ality.com -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.mozilla.org/pipermail/es-discuss/attachments/20130609/7a1c62d2/attachment-0001.html>