Proxy.handler-get.js 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. load("test-common.js");
  2. try {
  3. assert((new Proxy({}, { get: undefined })).foo === undefined);
  4. assert((new Proxy({}, { get: null })).foo === undefined);
  5. assert((new Proxy({}, {})).foo === undefined);
  6. let o = {};
  7. let p = new Proxy(o, {
  8. get(target, property, receiver) {
  9. assert(target === o);
  10. assert(property === "foo");
  11. assert(receiver === p);
  12. },
  13. });
  14. p.foo;
  15. o = { foo: 1 };
  16. p = new Proxy(o, {
  17. get(target, property, receiver) {
  18. if (property === "bar") {
  19. return 2;
  20. } else if (property === "baz") {
  21. return receiver.qux;
  22. } else if (property === "qux") {
  23. return 3;
  24. }
  25. return target[property];
  26. }
  27. });
  28. assert(p.foo === 1);
  29. assert(p.bar === 2);
  30. assert(p.baz === 3);
  31. assert(p.qux === 3);
  32. assert(p.test === undefined);
  33. // Invariants
  34. o = {};
  35. Object.defineProperty(o, "foo", { value: 5, configurable: false, writable: true });
  36. Object.defineProperty(o, "bar", { value: 10, configurable: false, writable: false });
  37. p = new Proxy(o, {
  38. get() {
  39. return 8;
  40. },
  41. });
  42. assert(p.foo === 8);
  43. assertThrowsError(() => {
  44. p.bar;
  45. }, {
  46. error: TypeError,
  47. message: "Proxy handler's get trap violates invariant: the returned value must match the value on the target if the property exists on the target as a non-writable, non-configurable own data property",
  48. });
  49. Object.defineProperty(o, "baz", { configurable: false, set(_) {} });
  50. assertThrowsError(() => {
  51. p.baz;
  52. }, {
  53. error: TypeError,
  54. message: "Proxy handler's get trap violates invariant: the returned value must be undefined if the property exists on the target as a non-configurable accessor property with an undefined get attribute",
  55. });
  56. console.log("PASS");
  57. } catch (e) {
  58. console.log("FAIL: " + e);
  59. }