|
| 1 | +function shouldBe(actual, expected) { |
| 2 | + if (actual !== expected) |
| 3 | + throw new Error(`bad value: ${actual}`); |
| 4 | +} |
| 5 | + |
| 6 | +function makePolyProtoObject() { |
| 7 | + function foo() { |
| 8 | + class C { |
| 9 | + constructor() { this._field = 42; } |
| 10 | + }; |
| 11 | + return new C; |
| 12 | + } |
| 13 | + for (let i = 0; i < 15; ++i) |
| 14 | + foo(); |
| 15 | + return foo(); |
| 16 | +} |
| 17 | + |
| 18 | +// A poly-proto object stores its prototype in the object rather than in its structure, so |
| 19 | +// Object.setPrototypeOf leaves its StructureID untouched. The Proxy handler-traps cache must not |
| 20 | +// treat a matching StructureID as proof that the prototype is still an object. |
| 21 | + |
| 22 | +{ |
| 23 | + let handler = makePolyProtoObject(); |
| 24 | + Object.setPrototypeOf(handler, Object.prototype); |
| 25 | + handler.get = (target, key) => `got ${key}`; |
| 26 | + |
| 27 | + let proxy = new Proxy({ }, handler); |
| 28 | + shouldBe(proxy.foo, "got foo"); |
| 29 | + |
| 30 | + Object.setPrototypeOf(handler, null); |
| 31 | + shouldBe(proxy.foo, "got foo"); |
| 32 | + shouldBe(proxy.bar, "got bar"); |
| 33 | +} |
| 34 | + |
| 35 | +{ |
| 36 | + let handler = makePolyProtoObject(); |
| 37 | + Object.setPrototypeOf(handler, Object.prototype); |
| 38 | + |
| 39 | + let proxy = new Proxy({ a: 1 }, handler); |
| 40 | + shouldBe(Object.keys(proxy).join(), "a"); |
| 41 | + |
| 42 | + Object.setPrototypeOf(handler, null); |
| 43 | + shouldBe(Object.keys(proxy).join(), "a"); |
| 44 | + |
| 45 | + handler.ownKeys = () => ["b"]; |
| 46 | + handler.getOwnPropertyDescriptor = () => ({ value: 2, enumerable: true, configurable: true }); |
| 47 | + shouldBe(Object.keys(proxy).join(), "b"); |
| 48 | +} |
| 49 | + |
| 50 | +{ |
| 51 | + let handler = makePolyProtoObject(); |
| 52 | + Object.setPrototypeOf(handler, Object.prototype); |
| 53 | + handler.get = function (target, key) { |
| 54 | + Object.setPrototypeOf(handler, null); |
| 55 | + return 42; |
| 56 | + }; |
| 57 | + |
| 58 | + let proxy = new Proxy({ }, handler); |
| 59 | + shouldBe(proxy.foo, 42); |
| 60 | + shouldBe(proxy.foo, 42); |
| 61 | +} |
| 62 | + |
| 63 | +// A poly-proto handler whose prototype gains a trap must pick the new trap up. |
| 64 | +{ |
| 65 | + let handler = makePolyProtoObject(); |
| 66 | + Object.setPrototypeOf(handler, Object.prototype); |
| 67 | + |
| 68 | + let proxy = new Proxy({ foo: 1 }, handler); |
| 69 | + shouldBe(proxy.foo, 1); |
| 70 | + |
| 71 | + Object.setPrototypeOf(handler, { get: () => "from prototype" }); |
| 72 | + shouldBe(proxy.foo, "from prototype"); |
| 73 | +} |
0 commit comments