Standard builtins' prototypes and toString

Mark S. Miller erights at google.com
Thu Jun 12 07:57:05 PDT 2014


Wow, what a mess. Let's forget the builtins for a moment and focus on JS
classes, both the old/current patterns for coding these manually, and the
new ES6 class syntax. Consider:

class Point {
  constructor(x, y) {
    this.x = x;
    this.y = y;
  },
  getX() { return this.x; },
  getY() { return this.y; },
  toString() {
    return `<${this.getX()},${this.getY()}>`;
  }
}

or equivalently enough in ES5

function Point(x, y) {
  this.x = x;
  this.y = y;
}
Point.prototype = {
  getX: function() { return this.x; },
  getY: function() { return this.y; },
  toString: function() {
    return '<' + this.getX() + ',' + this.getY() + '>';
  }
};

alert(Point.prototype) alerts "<undefined,undefined>". Ok, this specific
example doesn't throw, but equally simple and plausible examples would.





On Thu, Jun 12, 2014 at 5:26 AM, Till Schneidereit <
till at tillschneidereit.net> wrote:

> While working on changing Date.prototype to be a plain object in
> SpiderMonkey, we realized that there's an issue: the way things are specced
> now, `alert(Date.prototype)` will throw, because `Date.prototype.toString`
> isn't generic. The same applies for all builtins with non-generic
> `toString` prototype functions.
>
> To resolve this, I propose changing these `toString` to first check if the
> `this` value is %FooPrototype% (e.g., %DatePrototype% in the case at hand)
> and return the result of the equivalent of calling the original
> Object.prototype.toString.
>
> I'm not sure if that is enough to cover subclasses of these builtins. Will
> calling `toString` on the prototype of `class MyDate extends Date{}` still
> throw? If so, that would at least not be a backwards-compatibility concern,
> but it's probably also not desirable.
>
>
> till
>
> _______________________________________________
> es-discuss mailing list
> es-discuss at mozilla.org
> https://mail.mozilla.org/listinfo/es-discuss
>
>


-- 
    Cheers,
    --MarkM
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.mozilla.org/pipermail/es-discuss/attachments/20140612/526f0dcc/attachment-0001.html>


More information about the es-discuss mailing list