class-static-01.js (2467B)
1 // |jit-test| 2 load(libdir + "asserts.js"); 3 4 // Parse 5 class A { 6 static { } 7 }; 8 9 // Run 10 var ran = false; 11 class B { 12 static { 13 ran = true; 14 } 15 }; 16 17 assertEq(ran, true); 18 19 // Can access static assigned before. 20 var res; 21 class C { 22 static x = 10; 23 static { 24 res = this.x; 25 } 26 }; 27 28 assertEq(res, 10); 29 30 // Multiple static blocks 31 class D { 32 static { } 33 static { } 34 }; 35 36 class D1 { 37 static { } static { } 38 }; 39 40 // Blocks run in order. 41 class E { 42 static { 43 res = 10; 44 } 45 static { 46 assertEq(res, 10); 47 res = 14; 48 } 49 } 50 51 assertEq(res, 14); 52 53 54 // Can use static to access private state. 55 let accessor; 56 class F { 57 #x = 10 58 static { 59 accessor = (o) => o.#x; 60 } 61 } 62 63 let f = new F; 64 assertEq(accessor(f), 10); 65 66 class G { 67 static { 68 this.a = 10; 69 } 70 } 71 assertEq(G.a, 10); 72 73 // Can use the super-keyword to access a static method in super class. 74 class H { 75 static a() { return 101; } 76 } 77 78 class I extends H { 79 static { 80 res = super.a(); 81 } 82 } 83 84 assertEq(res, 101); 85 86 // Can add a property to a class from within a static 87 class J { 88 static { 89 this.x = 12; 90 } 91 } 92 93 assertEq(J.x, 12); 94 95 96 function assertThrowsSyntaxError(str) { 97 assertThrowsInstanceOf(() => eval(str), SyntaxError); // Direct Eval 98 assertThrowsInstanceOf(() => (1, eval)(str), SyntaxError); // Indirect Eval 99 assertThrowsInstanceOf(() => Function(str), SyntaxError); // Function 100 } 101 102 assertThrowsSyntaxError(` 103 class X { 104 static { 105 arguments; 106 } 107 } 108 `) 109 110 111 assertThrowsSyntaxError(` 112 class X extends class {} { 113 static { 114 super(); // can't call super in a static block 115 } 116 } 117 `) 118 119 assertThrowsSyntaxError(` 120 class X { 121 static { 122 return 10; // Can't return in a static block 123 } 124 } 125 `) 126 127 assertThrowsSyntaxError(` 128 class X { 129 static { 130 await 10; // Can't await in a static block 131 } 132 } 133 `) 134 135 // Can't await inside a static block, even if we're inside an async function. 136 // 137 // The error message here is not good `SyntaxError: await is a reserved identifier`, 138 // but can be fixed later. s 139 assertThrowsSyntaxError(` 140 async function f() { 141 class X { 142 static { 143 await 10; // Can't await in a static block 144 } 145 } 146 } 147 `) 148 149 150 assertThrowsSyntaxError(` 151 class X { 152 static { 153 yield 10; // Can't yield in a static block 154 } 155 } 156 `) 157 158 159 assertThrowsSyntaxError(` 160 function* gen() { 161 class X { 162 static { 163 yield 10; // Can't yield in a static block, even inside a generator 164 } 165 } 166 } 167 `) 168 169 // Incomplete should throw a sensible error. 170 assertThrowsSyntaxError(` 171 class A { static { this.x 172 `)