Default @@toStringTag for user classes

Dmitry Soshnikov dmitry.soshnikov at gmail.com
Tue Dec 2 17:12:30 PST 2014


On Tue, Dec 2, 2014 at 9:56 AM, Andrea Giammarchi <
andrea.giammarchi at gmail.com> wrote:

> I think by `@@toStringTag` he meant the ability to define a `[[Class]]`
> name so that `{}.toString.call(generic)` would return such name instead of
> `Object` but I'm sure Dmitry will come back explaining and/or asking more.
>

Yeah, so basically current `O.p.toString` [1] in step 14 delegates to the
`@@toStringTag`. Which means user-classes have ability to ad-hoc the result
of using _default_ `toString` from `O.p`.

In a class users have to put it manually at the moment:

```
class Point {
  constructor(x, y) {
    this._x = x;
    this._y = y;
  }

  toString() {
    return '<Point ' + this._x + ', ' + this._y + '>';
  }

  [Symbol.toStringTag]() {
    return 'Point';
  }
}

var p = new Point(10, 20);

console.log(p.toString()); // '<Point 10, 20>'
console.log(({}).toString.call(p)); // '[object Point]'
```

Notice how the implementation defines its own `toString`, and at the same
time provides the ability to test the type tag with the `O.p.toString`.

So my proposal is to provide default implicit implementation of that
`Symbol.toStringTag` method (which is `@@toStringTag` in the spec).

Dmitry

[1]
https://people.mozilla.org/~jorendorff/es6-draft.html#sec-object.prototype.tostring


>
> On Tue, Dec 2, 2014 at 4:49 PM, Claude Pache <claude.pache at gmail.com>
> wrote:
>
>>
>> > Le 2 déc. 2014 à 08:46, Dmitry Soshnikov <dmitry.soshnikov at gmail.com>
>> a écrit :
>> >
>> > Hi,
>> >
>> > Probably worth providing a default implementation of the
>> `@@toStringTag` when evaluating a class [1]. In this case users will be
>> able to do:
>> >
>> > ```
>> > class Point { ... }
>> >
>> > var p = new Point(1, 2);
>> > console.log(p); // "[object Point]"
>> > ```
>>
>> You seem to imply that  `console.log(p)` will show the result of
>> `p.toString()` in the console. But it is not the case for the majority of
>> browsers.
>>
>> I've just tried:
>>
>> ```
>> var Point = function() {}
>> Point.prototype.toString = function() { return "(this is an object of
>> type Point)" }
>> console.log(new Point)
>> ```
>>
>> Results are:
>>
>> Firefox: Object { }
>> Chrome: Point{toString: function}
>> Safari: Object
>> IE: [object Object]    (this is an object of type Point)
>>
>> In particular, note that Chrome doesn't need the help of `.toString()` in
>> order to log useful information.
>>
>> —Claude
>> _______________________________________________
>> es-discuss mailing list
>> es-discuss at mozilla.org
>> https://mail.mozilla.org/listinfo/es-discuss
>>
>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.mozilla.org/pipermail/es-discuss/attachments/20141202/8db0343d/attachment.html>


More information about the es-discuss mailing list