javascript入门

What is a JavaScript proxy? you might ask. It is one of the features that shipped with ES6. Sadly, it seems not to be widely used.

什么是JavaScript代理? 你可能会问。 这是ES6附带的功能之一。 可悲的是,它似乎并未得到广泛使用。

According to the MDN Web Docs:

根据MDN网络文档 :

The Proxy object is used to define custom behavior for fundamental operations (e.g. property lookup, assignment, enumeration, function invocation, etc).

Proxy对象用于定义基本操作的自定义行为(例如,属性查找,赋值,枚举,函数调用等)。

In simple terms, proxies are getters and setters with lots of swag. A proxy object sits between an object and the outside world. They intercept calls to the attributes and methods of an object even if those attributes and methods don’t exist.

简单来说,代理是gettersetter方法有很多赃物。 代理对象位于对象和外界之间。 即使对象属性和方法不存在,它们也会拦截对它们的调用。

For us to understand how proxies work, we need to define three terms used by proxies:

为了让我们理解代理的工作方式,我们需要定义代理使用的三个术语:

  1. handler: The placeholder object which contains traps (they’re the interceptors).

    handler :包含陷阱的占位符对象(它们是拦截器)。

  2. traps: The methods that provide property access (they live inside the handler).

    traps :提供属性访问的方法(它们位于处理程序内部)。

  3. target: The object which the proxy virtualizes.

    target :代理虚拟化的对象。

句法 (Syntax)

let myProxy = new Proxy(target, handler);

为什么要代理? (Why proxies?)

Since proxies are similar to getters and setters, why should we use them? Let’s see why:

由于代理类似于gettersetter,我们为什么要使用它们? 让我们看看为什么:

const staff = {_name: "Jane Doe",_age: 25,get name() {console.log(this._name);},get age() {console.log(this._age);},set age(newAge) {this._age = newAge;console.log(this._age)}
};
staff.name // => "Jane Doe"
staff.age // => 25
staff.age = 30
staff.age // => 30
staff.position // => undefined

Let’s write the same code with proxies:

让我们用代理编写相同的代码:

const staff = {name: "Jane Doe",age: 25
}
const handler = {get: (target, name) => {name in target ? console.log(target[name]) : console.log('404 not found');},set: (target, name, value) => {target[name] = value;}
}
const staffProxy = new Proxy(staff, handler);
staffProxy.name // => "Jane Doe"
staffProxy.age // => 25
staffProxy.age = 30
staffProxy.age // => 30
staffProxy.position // => '404 not found'

In the above example using getters and setters, we have to define a getter and setter for each attribute in the staff object. When we try to access a non-existing property, we get undefined.

在上面的使用gettersetter的示例中,我们必须为staff对象中的每个属性定义一个gettersetter 。 当我们尝试访问不存在的属性时,我们得到undefined

With proxies, we only need one get and set trap to manage interactions with every property in the staff object. Whenever we try to access a non-existing property, we get a custom error message.

使用代理,我们只需要一个get and set陷阱即可管理与staff对象中每个属性的交互。 每当我们尝试访问不存在的属性时,都会收到自定义错误消息。

There are many other use cases for proxies. Let’s explore some:

代理还有许多其他用例。 让我们探索一些:

代理验证 (Validation with proxies)

With proxies, we can enforce value validations in JavaScript objects. Let’s say we have a staff schema and would like to perform some validations before a staff can be saved:

使用代理,我们可以在JavaScript对象中强制执行值验证。 假设我们有一个staff模式,并且希望在保存职员之前执行一些验证:

const validator = {set: (target, key, value) => {const allowedProperties = ['name', 'age', 'position'];if (!allowedProperties.includes(key)) {throw new Error(`${key} is not a valid property`)}if (key === 'age') {if (typeof value !== 'number' || Number.isNaN(value) || value <= 0) {throw new TypeError('Age must be a positive number')}}if (key === 'name' || key === 'position') {if (typeof value !== 'string' || value.length <= 0) {throw new TypeError(`${key} must be a valid string`)}}target[key] = value; // save the valuereturn true; // indicate success}
}
const staff = new Proxy({}, validator);
staff.stats = "malicious code" //=> Uncaught Error: stats is not a valid property
staff.age = 0 //=> Uncaught TypeError: Age must be a positive number
staff.age = 10
staff.age //=> 10
staff.name = '' //=> Uncaught TypeError: name must be a valid string

In the code snippet above, we declare a validator handler where we have an array of allowedProperties. In the set trap, we check if the key being set is part of our allowedProperties. If it’s not, we throw an error. We also check if the values being set are of certain data types before we save the value.

在上面的代码片段中,我们声明了一个validator处理程序,其中有一个allowedProperties数组。 在set陷阱中,我们检查设置的键是否是我们allowedProperties一部分。 如果不是,则抛出错误。 在保存值之前,我们还检查设置的值是否属于某些数据类型。

可撤销代理 (Revocable proxies)

What if we wanted to revoke access to an object? Well, JavaScript proxies have a Proxy.revocable() method which creates a revocable proxy. This gives us the ability to revoke access to a proxy. Let’s see how it works:

如果我们想撤消对某个对象的访问该怎么办? 嗯,JavaScript代理具有Proxy.revocable()方法,该方法创建可撤消的代理。 这使我们能够撤消对代理的访问。 让我们看看它是如何工作的:

const handler = {get: (target, name) => {name in target ? console.log(target[name]) : console.log('404 not found');console.log(target)},set: (target, name, value) => {target[name] = value;}
}
const staff = {name: "Jane Doe",age: 25
}
let { proxy, revoke } = Proxy.revocable(staff, handler);
proxy.age // => 25
proxy.name // => "Jane Doe"
proxy.age = 30
proxy.age // => 30
revoke() // revoke access to the proxy
proxy.age // => Uncaught TypeError: Cannot perform 'get' on a proxy that has been revoked
proxy.age = 30 // => Uncaught TypeError: Cannot perform 'set' on a proxy that has been revoked

In the example above, we are using destructuring to access theproxy and revoke properties of the object returned by Proxy.revocable().

在上面的示例中,我们使用解构来访问proxyrevoke Proxy.revocable()返回的对象的属性。

After we call the revoke function, any operation applied to proxy causes a TypeError. With this in our code, we can prevent users from taking certain actions on certain objects.

调用revoke函数后,应用于proxy任何操作都会导致TypeError 。 使用此代码,我们可以防止用户对某些对象执行某些操作。

JavaScript proxies are a powerful way to create and manage interactions between objects. Other real world applications for Proxies include:

JavaScript代理是创建和管理对象之间的交互的强大方法。 代理的其他实际应用程序包括:

  • Extending constructors扩展构造函数
  • Manipulating DOM nodes操作DOM节点
  • Value correction and an extra property价值校正和额外的属性
  • Tracing property accesses跟踪属性访问
  • Trapping function calls陷阱函数调用

And the list goes on.

而这样的例子不胜枚举。

There’s more to proxies than we have covered here. You can check the Proxy MDN Docs to find out all the available traps and how to use them.

代理比我们在这里讨论的更多。 您可以检查“ 代理MDN文档”以找到所有可用的陷阱以及如何使用它们。

I hope you found this tutorial useful. Please do and share so others can find this article. Hit me up on Twitter @developia_ with questions or for a chat.

希望本教程对您有所帮助。 请分享,以便其他人可以找到本文。 通过问题或聊天在Twitter @d evelopia_上打我。

翻译自: https://www.freecodecamp.org/news/a-quick-intro-to-javascript-proxies-55695ddc4f98/

javascript入门

javascript入门_JavaScript代理快速入门相关推荐

  1. JavaScript学习记录01快速入门、基本语法、严格检查模式

    文章目录 JavaScript学习记录01快速入门.基本语法.严格检查模式 1.1什么是JavaScript 1.2认识JavaScript框架 1.3快速入门 1.4基本语法入门 1.5数据类型简介 ...

  2. python魔力手册-小白入门宝典:Python快速入门魔力手册 PDF 超清版

    给大家带来的一篇关于Python编程相关的电子书资源,介绍了关于小白入门.python入门.Python手册方面的内容,本书是由魔力手册出版,格式为PDF,资源大小11.8 MB,魔力手册编写,目前豆 ...

  3. Python零基础入门教程( 快速入门)

    前言 学无止境,无止境学. 今天要给大家分享的是<Python零基础入门教程01 快速入门>,这是一个系列的教程,从零基础到项目实战.在本教程中,我会给大家介绍Python入门的一些基础知 ...

  4. java web快速入门_Web安全快速入门

    java web快速入门 Web开发人员针对CORS,CSP,HSTS和所有Web安全首字母缩写词的入门知识! (A web developer's primer on CORS, CSP, HSTS ...

  5. boot入门思想 spring_SpringBoot快速入门

    一.Spring介绍 1.1.SpringBoot简介 在您第1次接触和学习Spring框架的时候,是否因为其繁杂的配置而退却了?在你第n次使用Spring框架的时候,是否觉得一堆反复黏贴的配置有一些 ...

  6. docker快速入门_Docker标签快速入门

    docker快速入门 by Shubheksha 通过Shubheksha Docker标签快速入门 (A quick introduction to Docker tags) If you've w ...

  7. ue4 迁移模型_UE4虚幻引擎学习云笔记(六)-关卡设计入门-[5.地形快速入门]

    [六.关卡设计入门(Level Designer Quick Start)] 19-09-29 UE4虚幻引擎学习云笔记(六)-关卡设计入门​zhuanlan.zhihu.com UE4虚幻引擎学习云 ...

  8. pkpm快速入门教程_PKPM快速入门教程.ppt

    PKPM快速入门教程.ppt PKPM快速入门 PMCAD的基本功能 一.人机交互建立全楼结构模型 二.自动倒算荷载建立恒活载库 三.为各种计算模型提供所需数据文件 四.为上部各绘图CAD模块提供结构 ...

  9. 【软件入门】STM32CubeMX快速入门

    更正 2022.07.03 发现2.4一节中代码位置有问题, 没有添加到*USER CODE BEGIN -和USER CODE END-*之间,这样对代码的运行不会产生影响,但是如果更新CubeMX ...

最新文章

  1. 如何构建虚拟护士应用程序?
  2. mysql的安装和启动_mysql安装和启动
  3. NetBeans 时事通讯(刊号 # 55 - May 06, 2009)
  4. unity检测范围内敌人_Unity实现视野范围外死亡敌人的分数显示在屏幕内
  5. 真正的研发之路(1)
  6. Java8(JDK1.8)新特性
  7. SPSS——统计描述
  8. 仿写京东登录页面HTML/CSS
  9. RAM的 Parity 与 ECC
  10. 高精度计算Π的值(C语言)
  11. C#textbox和label显示皆透明如何修改/让字体和背景透明
  12. word文档图标变成白纸_word图标变了_word图标变成白底方框
  13. 100-days: twenty-four
  14. 一台笔记本只有一个显卡,如何同时连接两台显示器
  15. BeyondCompare使用
  16. 使用EJS脚本实现花生壳动态域名更新服务(一)
  17. 史上最全的 axios 工具封装
  18. dns服务器添加新的dns_DNS服务器能否影响下载速度?
  19. Python随笔:用 json 进行 字符串和字典 数据类型的转换
  20. 嵌入式系统在物联网中的应用及架构

热门文章

  1. 【干货】mysql查询重复数据sql
  2. vue 中v-if 与v-show 的区别
  3. Node.js——异步上传文件
  4. Jquery的ajax提交成功后刷新页面
  5. PCH文件的创建和配置
  6. 灵动标签调用友情链接
  7. mysql数据库-mysql数据定义语言DDL (Data Definition Language)归类(六)
  8. java正则表达式提取字符串中的数字
  9. POJ 1380 坐标旋转
  10. Cookie操作以及如何在js中调用jsp变量