zoukankan      html  css  js  c++  java
  • [Javascript] Wrap a Javascript Built-in constructor with Proxy

    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);
  • 相关阅读:
    2020/3/21 简单的学习
    2020/3/7 A-B
    2020/3/6 旋转骰子
    2020/3/6 美丽数组
    面向对象程序设计寒假作业2
    自我介绍
    深度优先搜索-迷宫问题(走迷宫题解)
    开机方案题解
    好吃的巧克力题解
    数楼梯题解
  • 原文地址:https://www.cnblogs.com/Answer1215/p/13569153.html
Copyright © 2011-2022 走看看