Re: [heycam/webidl] Replace serializers by toJSON and [Default] extended attribute (#323)

tobie commented on this pull request.



> +
+    To invoke the <dfn export>default toJSON operation</dfn> of [=interface=] |I|,
+    run the the following steps:
+
+    1.  Let |O| be the <emu-val>this</emu-val> value.
+    1.  Let |result| be [=!=] [=ObjectCreate=]([=%ObjectPrototype%=]).
+    1.  If there is an [=inherited interface=] of |I|
+        that declares a “toJSON” operation, then
+        1.  Let |super| be the “toJSON” operation  of
+            the closest [=inherited interface=] of |I|
+            that declares a “toJSON” operation.
+        1.  Set |result| to [=?=] [=Call=](|super|, |O|).
+    1.  If Type(|result|) is not Object, return |result|.
+    1.  For each [=exposed=] [=regular attribute=] |attr| that is an [=interface member=] of |I|:
+        1.  Let |id| be |attr|’s [=identifier=] [=converted to an ECMAScript value=].
+        1.  Let |value| be [=?=] [=Get=](|O|, |id|).

The tricky bit, which is also the one I'm conceptually struggling the most with (if my understanding of it is correct), is that you want to be calling the getters of interface |I|, _which is not necessarily the one that |O| implements_. Consider the following example (@bzbarsky, stop me if I'm wrong):

```webidl
interface Grandparent {
  [Default] any toJSON();
  attribute DOMString x; // returns "gp-x"
};

interface Parent : Grandparent {
  [Default] any toJSON();
  attribute DOMString y; // returns "p-y"
};

interface Child {
  attribute DOMString x; // returns "c-x"
  attribute DOMString z; // returns "c-z"
};
```

```js
new GrandParent().toJSON();
// { x: "gp-x" };

new Parent().toJSON();
// { x: "gp-x", y: "p-y" };

new Child().toJSON();
// { x: "gp-x", y: "p-y" };
```

In the last example, notice how we called `Grandpa`'s getter for x, not `Child`'s. Also notice how z isn't stringified as `toJSON` isn't declared on `Child`.

Overall I see how that makes sense from an implementor's perspective, but coming from dynamic languages, I find that super hard to grasp and reason about.

-- 
You are receiving this because you are subscribed to this thread.
Reply to this email directly or view it on GitHub:
https://github.com/heycam/webidl/pull/323#discussion_r103980683

Received on Thursday, 2 March 2017 18:20:21 UTC