[Javascript] Wrap a Javascript Built-in constructor with Proxy
JavaScript in with Proxy constructor wrap built
2023-09-14 09:00:47 时间
Instances of most built-in constructors also use a mechanism that is not intercepted by Proxies. They therefore can’t be wrapped transparently, either. We can see that if we use an instance of Date
:
const proxy = new Proxy(new Date(), {}); assert.throws( () => proxy.getFullYear(), /^TypeError: this is not a Date object\.$/ );
The mechanism that is unaffected by Proxies is called internal slots. These slots are property-like storage associated with instances. The specification handles these slots as if they were properties with names in square brackets.
As a work-around, we can change how the handler forwards method calls and selectively set this
to the target and not the Proxy:
const handler = { get(target, propKey, receiver) { if (propKey === 'getFullYear') { return target.getFullYear.bind(target); } return Reflect.get(target, propKey, receiver); }, }; const proxy = new Proxy(new Date('2030-12-24'), handler); assert.equal(proxy.getFullYear(), 2030);
相关文章
- [Javascript] Understanding the difference between .prototype and .__proto__ in JavaScript
- [Javascript] Keyword 'in' to check prop exists on Object
- [Algorithm] Write your own Math.pow function in Javascript, using Recursive approach
- [Javascript] Deep merge in Javascript with Ramda.js mergeDeepWith
- [Javascript] Await a JavaScript Promise in an async Function with the await Operator
- [Unit Testing] Fundamentals of Testing in Javascript
- [Javascript] Identify and Deal with NaN in JavaScript
- [Javascript] Adding Shapes to Maps with Leaflet and GeoJSON
- [XState] Create Actor in Vanilla Javascript
- [Algorithms] Divide and Recurse Over an Array with Merge Sort in JavaScript
- [Algorithm] Write a Depth First Search Algorithm for Graphs in JavaScript
- [Javascript] Use JavaScript's for-in Loop on Objects with Prototypes
- [Javascript] Classify text into categories with machine learning in Natural
- [Javascript] Identify and Deal with NaN in JavaScript
- [Javascript] MetaProgramming: new.target
- escape in ABAP and JavaScript
- escape in ABAP and JavaScript
- 【华为OD机试 2023】 优选核酸检测点(C++ Java JavaScript Python)