class-private-fields.js 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. test("basic functionality", () => {
  2. class A {
  3. #number = 3;
  4. getNumber() {
  5. return this.#number;
  6. }
  7. #string = "foo";
  8. getString() {
  9. return this.#string;
  10. }
  11. #uninitialized;
  12. getUninitialized() {
  13. return this.#uninitialized;
  14. }
  15. }
  16. const a = new A();
  17. expect(a.getNumber()).toBe(3);
  18. expect(a.getString()).toBe("foo");
  19. expect(a.getUninitialized()).toBeUndefined();
  20. expect("a.#number").not.toEval();
  21. expect("a.#string").not.toEval();
  22. expect("a.#uninitialized").not.toEval();
  23. });
  24. test("initializer has correct this value", () => {
  25. class A {
  26. #thisVal = this;
  27. getThisVal() {
  28. return this.#thisVal;
  29. }
  30. #thisName = this.#thisVal;
  31. getThisName() {
  32. return this.#thisName;
  33. }
  34. }
  35. const a = new A();
  36. expect(a.getThisVal()).toBe(a);
  37. expect(a.getThisName()).toBe(a);
  38. });
  39. test("static fields", () => {
  40. class A {
  41. static #simple = 1;
  42. static getStaticSimple() {
  43. return this.#simple;
  44. }
  45. static #thisVal = this;
  46. static #thisName = this.name;
  47. static #thisVal2 = this.#thisVal;
  48. static getThisVal() {
  49. return this.#thisVal;
  50. }
  51. static getThisName() {
  52. return this.#thisName;
  53. }
  54. static getThisVal2() {
  55. return this.#thisVal2;
  56. }
  57. }
  58. expect(A.getStaticSimple()).toBe(1);
  59. expect(A.getThisVal()).toBe(A);
  60. expect(A.getThisName()).toBe("A");
  61. expect(A.getThisVal2()).toBe(A);
  62. expect("A.#simple").not.toEval();
  63. });
  64. test("cannot have static and non static field with the same description", () => {
  65. expect("class A { static #simple; #simple; }").not.toEval();
  66. });