private-accessors.js 2.12 KB
Newer Older
1 2 3 4 5 6 7 8
// Copyright 2019 the V8 project authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

"use strict";

// Complementary private accessors.
{
9
  let store = 1;
10
  class C {
11 12 13 14 15
    get #a() { return store; }
    set #a(val) { store = val; }
    incA() { this.#a++; }  // CountOperation
    setA(val) { this.#a = val; }
    getA() { return this.#a; }
16 17
  }

18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42
  const c = new C;
  assertEquals(store, c.getA());
  assertEquals(1, c.getA());
  c.setA(2);
  assertEquals(store, c.getA());
  assertEquals(2, c.getA());
  c.incA();
  assertEquals(store, c.getA());
  assertEquals(3, c.getA());
}

// Compound assignment.
{
  let store;
  class A {
    get #a() { return store; }
    set #a(val) { store = val; }
    getA() { return this.#a; }
    constructor(val) {
      ({ y: this.#a } = val);
    }
  }

  const a = new A({y: 'test'});
  assertEquals('test', a.getA());
43 44
}

45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64
// Accessing super in private accessors.
{
  class A { foo(val) {} }
  class C extends A {
    set #a(val) { super.foo(val); }
  }
  new C();

  class D extends A {
    get #a() { return super.foo; }
  }
  new D();

  class E extends A {
    set #a(val) { super.foo(val); }
    get #a() { return super.foo; }
  }
  new E();
}

65 66 67 68
// Nested private accessors.
{
  class C {
    get #a() {
69 70 71 72 73 74
      let storeD = 'd';
      class D {
        // Shadows outer #a
        get #a() { return storeD; }
        getD() { return this.#a; }
      }
75 76
      return new D;
    }
77 78 79
    getA() {
      return this.#a;
    }
80
  }
81
  assertEquals('d', new C().getA().getD());
82 83
}

84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107
{
  assertThrows(() => {
    class A {
      [this.#a] = 1;
      get #a() {}
    }
  }, TypeError);

  assertThrows(() => {
    class A {
      [this.#a] = 1;
      set #a(val) {}
    }
  }, TypeError);

  assertThrows(() => {
    class A {
      [this.#a] = 1;
      set #a(val) {}
      get #a() {}
    }
  }, TypeError);
}

108 109 110 111 112 113
// Duplicate private accessors.
// https://tc39.es/proposal-private-methods/#sec-static-semantics-early-errors
{
  assertThrows('class C { get #a() {} get #a() {} }', SyntaxError);
  assertThrows('class C { set #a(val) {} set #a(val) {} }', SyntaxError);
}