ES6代理的主要用例 [英] Major use cases for ES6 proxies

查看:80
本文介绍了ES6代理的主要用例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近了解了ES6代理,但我认为没有充分的理由使用它.我的意思是,没有代理人可以做的所有事情都可以完成,除非我丢失了某些东西.

I recently got to know about ES6 proxies but I don't see a good reason to use it. I mean, everything that one could do with Proxy can be done without it, except if I'm missing something.

例如,大多数人在谈到代理时都谈论验证,但是有人可以运用一些JS优点来进行验证,每个人都很好.如果有人能对代理的一些主要用例睁开眼睛,我将不胜感激.谢谢!

For example, most folks talk about validation when it comes to proxy but one could apply some JS goodness to validate and everyone is fine. I would appreciate if someone could open my eyes to some major use cases of Proxies. Thanks!

推荐答案

我的意思是,没有它,代理人可以做的每件事...

I mean, every thing that one could do with Proxy can be done without it...

那不是真的.

考虑一般需要捕获对不存在的属性的访问:

Consider the common need to catch access to properties that don't exist:

const o = {foo: "bar"};
console.log(o.blarg);

通常以不同于默认方式(登录undefined)的方式进行处理.通过 get陷阱.示例:

It's common to want to handle that in a way other than the default, which is to log undefined. Proxy lets us do that, via the get trap. Example:

const o = {foo: "bar"};
const p = new Proxy(o, {
  get(target, prop, receiver) {
    return prop in target ? target[prop] : "nifty!";
  }
});
console.log(p.foo);
console.log(p.blarg);

另一个例子是能够挂接到获取对象属性列表的各种操作中的能力.没有代理,就没有办法迷上它. 使用代理很容易:您使用 has陷阱

Another example is the ability to hook into the various operations that get the list of properties on an object. There is no way to hook into that without Proxy. With Proxy, it's easy: You use the has trap or the ownKeys trap depending on what you want to hook into.

在其他用例方面:代理是实现Facade模式的最终工具.查找Facade的用例,您将找到Proxy的用例.

In terms of other use cases: Proxy is the ultimate tool for implementing the Facade pattern. Look for the use cases of Facade, and you'll find use cases for Proxy.

这篇关于ES6代理的主要用例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆