summaryrefslogtreecommitdiff
path: root/Userland/Libraries/LibJS/Tests/classes/class-private-fields.js
blob: 06cf102a6d68cfb051a01397d8028663cb9d99e4 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
test("basic functionality", () => {
    class A {
        #number = 3;

        getNumber() {
            return this.#number;
        }

        #string = "foo";

        getString() {
            return this.#string;
        }

        #uninitialized;

        getUninitialized() {
            return this.#uninitialized;
        }
    }

    const a = new A();
    expect(a.getNumber()).toBe(3);
    expect(a.getString()).toBe("foo");
    expect(a.getUninitialized()).toBeUndefined();

    expect("a.#number").not.toEval();
    expect("a.#string").not.toEval();
    expect("a.#uninitialized").not.toEval();
});

test("initializer has correct this value", () => {
    class A {
        #thisVal = this;

        getThisVal() {
            return this.#thisVal;
        }

        #thisName = this.#thisVal;

        getThisName() {
            return this.#thisName;
        }
    }

    const a = new A();
    expect(a.getThisVal()).toBe(a);
    expect(a.getThisName()).toBe(a);
});

test("static fields", () => {
    class A {
        static #simple = 1;

        static getStaticSimple() {
            return this.#simple;
        }

        static #thisVal = this;
        static #thisName = this.name;
        static #thisVal2 = this.#thisVal;

        static getThisVal() {
            return this.#thisVal;
        }

        static getThisName() {
            return this.#thisName;
        }

        static getThisVal2() {
            return this.#thisVal2;
        }
    }

    expect(A.getStaticSimple()).toBe(1);

    expect(A.getThisVal()).toBe(A);
    expect(A.getThisName()).toBe("A");
    expect(A.getThisVal2()).toBe(A);

    expect("A.#simple").not.toEval();
});

test("cannot have static and non static field with the same description", () => {
    expect("class A { static #simple; #simple; }").not.toEval();
});