Skip to content

Instantly share code, notes, and snippets.

@mheiber
Last active July 18, 2019 16:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mheiber/2d81a88e4030c3dc765894120453f734 to your computer and use it in GitHub Desktop.
Save mheiber/2d81a88e4030c3dc765894120453f734 to your computer and use it in GitHub Desktop.

Should this error?

class Parent {
  #foo;
  copy(instance) {
    this.#foo = instance.foo;
  }
}
class Child extends Parent {}
const parent = new Parent();
const child = new Child();
parent.copy(new Parent()); // OK
parent.copy(child); // error ?

'No error' because:

The Parent's foo is being looked up on the child. Since child is an instance of Parent, Parent should be able to treat it like any other instance.

'This should error' because:

First, this is how property access works with normal properties:

  • [[Get]] is called (link)
  • if the object is normal, [[OrdinaryGet]] is called (link)
  • OrdinaryGet does a [[HasProperty]] on the object. if not found, repeats the process up the prototype chain until the property is found or there are not more parents.

Lookup for private fields is different!

  • PrivateFieldGet is called (link)
  • which calls [[PrivateFieldFind]] (link)
  • PrivateFieldFind is just returns O.[[PrivateFieldValues]] or empty. There is no mention of prototypes

So the only way the prototype chain could be relevant is if at some point private fields from the parent are added to the child. This doesn't seem to happen. The call graph in the spec is something like:

-> [[Construct]] -> InitializeInstanceFields -> DefineField -> PrivateFieldAdd

and [[PrivateFieldAdd]] doesn't mention prototypes (link)

So according to my interpretation of the spec, the property should not be found and the lines commented above should

What do implmementors do:

  • No error: Chrome Canary, Babel plugin

  • Error: TS implementation (WIP)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment