xgqfrms™, xgqfrms® : xgqfrms's offical website of cnblogs! xgqfrms™, xgqfrms® : xgqfrms's offical website of GitHub!

js ES6 Proxy All In One

js ES6 Proxy All In One

The Proxy object enables you to create a proxy for another object, which can intercept and redefine fundamental operations for that object.

Proxy 对象使您能够为另一个对象创建代理,该代理可以拦截和重新定义该对象的基本操作。

Proxy

const target = {
  message1: "hello",
  message2: "everyone"
};
const handler = {};

const proxy = new Proxy(target, handler);

console.log(proxy.message1);
// hello
console.log(proxy.message2); 
// everyone

const target = {
  message1: "hello",
  message2: "everyone"
};

const handler = {
  get(target, prop, receiver) {
    // 拦截
    return "world";
  }
};

const proxy = new Proxy(target, handler);

console.log(proxy.message1); 
// world
console.log(proxy.message2); 
// world

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy

Reflect

const target = {
  message1: "hello",
  message2: "everyone"
};

const handler = {
  get(target, prop, receiver) {
    if (prop === "message2") {
      return "world";
    }
    // Reflect ✅
    return Reflect.get(...arguments);
  },
};

const proxy = new Proxy(target, handler);

console.log(proxy.message1); 
// hello
console.log(proxy.message2); 
// world


https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Reflect

refs

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects#reflection



©xgqfrms 2012-2020

www.cnblogs.com/xgqfrms 发布文章使用:只允许注册用户才可以访问!

原创文章,版权所有©️xgqfrms, 禁止转载 🈲️,侵权必究⚠️!


posted @ 2022-02-13 23:17  xgqfrms  阅读(32)  评论(0编辑  收藏  举报