|
| 1 | +// This is simple object. |
| 2 | +const someObject = { |
| 3 | + prop1: "Property One", |
| 4 | + prop2: 1 |
| 5 | +} |
| 6 | + |
| 7 | +// This is proxy object. |
| 8 | +const objectProxy = new Proxy(someObject, { |
| 9 | + get (target, prop) { |
| 10 | + console.log(`Target is ${target}`); |
| 11 | + console.log(`Prop is ${prop}`); |
| 12 | + return target[prop]; |
| 13 | + }, |
| 14 | + set (target, prop, value) { |
| 15 | + if (prop in target) { |
| 16 | + target[prop] = value; |
| 17 | + } else { |
| 18 | + throw new Error("Bad prop."); |
| 19 | + } |
| 20 | + }, |
| 21 | + has (target, prop) { |
| 22 | + return ["prop1", "prop2"].includes(prop); |
| 23 | + }, |
| 24 | + deleteProperty(target, prop) { |
| 25 | + delete target[prop]; |
| 26 | + return true; |
| 27 | + } |
| 28 | +}); |
| 29 | + |
| 30 | +// This is simple function. |
| 31 | +// const someFunc = text => console.log(text); |
| 32 | +const someFunc = function(text) { |
| 33 | + console.log(text); |
| 34 | +} |
| 35 | + |
| 36 | +// This is proxy function. |
| 37 | +const funcProxy = new Proxy(someFunc, { |
| 38 | + apply(target, thisArg, args) { |
| 39 | + console.log(`Target is: ${target}`); |
| 40 | + console.log(`This arg is: ${thisArg}`); |
| 41 | + console.log(`Args is: ${args}`); |
| 42 | + |
| 43 | + return target.apply(thisArg, args).toUpperCase(); |
| 44 | + } |
| 45 | +}); |
| 46 | + |
| 47 | +// This is simple class. |
| 48 | +class SomeClass { |
| 49 | + constructor(prop1, prop2) { |
| 50 | + this.prop1 = prop1; |
| 51 | + this.prop2 = prop2; |
| 52 | + } |
| 53 | +} |
| 54 | + |
| 55 | +// This is proxy class. |
| 56 | +const ClassProxy = new Proxy(SomeClass, { |
| 57 | + construct(target, args) { |
| 58 | + return new Proxy(new target(...args), { |
| 59 | + get (t, prop) { |
| 60 | + console.log(prop); |
| 61 | + return t[prop]; |
| 62 | + } |
| 63 | + }) |
| 64 | + } |
| 65 | +}); |
| 66 | + |
| 67 | +const proxy = new ClassProxy("Some property", 123); |
0 commit comments