Overriding Map/etc with get/set hooks?
allen at wirfs-brock.com
Mon Aug 11 19:50:27 PDT 2014
On Aug 11, 2014, at 5:55 PM, Tab Atkins Jr. wrote:
> Restarting this thread, because it's still an issue a year+ on.
> In the Font Loading spec <http://dev.w3.org/csswg/css-font-loading/>,
> I have a FontFaceSet interface
> which is a Set that contains FontFace objects, plus a few other
> methods and attributes.
> Except that it's not a Set, because I can't subclass Sets reliably.
> Instead, I have to duplicate the entire Set interface *as it exists
> today*, and have it delegate to a hidden internal Set object. This
> means that when TC39 extends the Set interface, FontFaceSet will have
> to be manually updated and bugfixed to contain its own version of the
> new methods. It also means that when authors define new methods on
> Set.prototype, they don't apply to FontFaceSet objects unless they
> manually copy them to FontFaceSet.prototype as well.
> This is obviously bad. But I can't just directly subclass Set. If I
> do, then authors can do Set.prototype.add(ffset, "hahaha, I'm a
> string, not a font face!"), and then the Set is corrupted. I could,
> of course, defensively write all the FFS operations to check each
> entry for being a FontFace object first, but that's not quite enough,
> because *authors* also have to do this when iterating a FFS.
> It's accepted and idiomatic for all sorts of methods in the web
> platform to do typechecks on their arguments, and throw errors when
> they don't match what's expected. It's impossible for me to robustly
> do this for the Set and Map methods, though. Can we come up with
> something that allows me to enforce these kinds of checks, like I'm
> currently doing with my Set-lookalike, and like we do everywhere else
> in the entire web platform?
You can imaging the specification of Set being enhanced to include a private slot whose value was a function that was used to validate values that were being added to the set. Such a function could be (optionally) set when a set is created and would be called by the built-in add method. Somebody might want to develop a proposal for ES7. I think it could be done in a manner that was backwards compatible with the E#S6 Set spec. You could also do something similar with Map and a function that validates both keys and values.
More information about the es-discuss