javascript入门_JavaScript代理快速入门

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入门

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/393852.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

linux缺少文件操作数,linux 文件的atime,ctime,mtime查看与修改

查看ls -a默认显示的是修改时间ls -c / --timestatus / --timectime显示的是状态修改时间(即权限修改时间)ls -u / --timeuse / --timeaccess / --timeatime表示的是文件访问时间修改touch: 缺少了文件操作数请尝试执行“touch --help”来获取更多信息。[weilocalhost ~]$ touc…

leetcode47. 全排列 II(回溯)

给定一个可包含重复数字的序列&#xff0c;返回所有不重复的全排列。 示例: 输入: [1,1,2] 输出: [ [1,1,2], [1,2,1], [2,1,1] ] 代码 class Solution {List<List<Integer>> cListnew ArrayList<>();public List<List<Integer>> permuteUni…

linux 磁盘查看方式

fdisk (查看物理磁盘大小) df (查看文件系统&#xff0c;也就是正在使用磁盘大小) lsblk (查看逻辑磁盘大小)转载于:https://www.cnblogs.com/MUQINGFENG123/p/10820345.html

ioslabel阴影,UILabel的内阴影

is it possible to create such a UILabel with inner and outer shadow?i only know shadowColor and shadowOffsetzoomed:thanks!解决方案The answer by dmaclach is only suitable for shapes that can easily be inverted. My solution is a custom view that works with …

Webpack初学者介绍

Webpack is a tool that lets you compile JavaScript modules. It’s also known as a module bundler.Webpack是使您可以编译JavaScript模块的工具。 也称为模块捆绑器 。 Given a large number of files, it generates a single file (or a few files) that run your app.给…

Android Coding利器之掌握小技巧,助你Coding更上一层楼~

本文讲的是Android Coding利器之掌握小技巧&#xff0c;助你Coding更上一层楼~&#xff0c;话说前几天在网上浏览到一大牛写的关于Android布局优化的文章&#xff0c;看后感触很深&#xff0c;回过头看看自己写过的代码&#xff0c;发现还是有不少需要改进&#xff0c;今天找不…

linux系统报警怎么办,常见Linux系统故障和解决方法

常见Linux系统故障和解决方法发布时间&#xff1a;2020-06-06 14:48:19来源&#xff1a;亿速云阅读&#xff1a;212作者&#xff1a;Leah栏目&#xff1a;云计算这篇文章给大家分享的是常见的Linux系统故障和解决方法。在使用系统的过程中总会有各种各样的故障&#xff0c;所以…

Vuex 模块化与项目实例 (2.0)

Vuex 强调使用单一状态树&#xff0c;即在一个项目里只有一个 store&#xff0c;这个 store 集中管理了项目中所有的数据以及对数据的操作行为。但是这样带来的问题是 store 可能会非常臃肿庞大不易维护&#xff0c;所以就需要对状态树进行模块化的拆分。 首先贴出一个逻辑比较…

click js自动点击 vue_vue.js2.0点击获取自己的属性和jquery方法

如下所示&#xff1a;:data-index"index":dt"index"v-on:click"onclick($event,index)":data-d "JSON.stringify( item)"href"http://www.baidu.com" rel"external nofollow" rel"external nofollow"da…

Python:知识目录

Python目录 第一篇&#xff1a;数据类型部分文件操作 基础数据类型---str 基础数据类型---List 基础数据类型---dict 基础数据类型---set 基础数据类型---bytes 数据类型的总结 文件操作------读&#xff0c;写 文件操作------使用方法 第二章&#xff1a;函数模块 初识函数…

初学者css常见问题_5分钟内学习CSS-初学者教程

初学者css常见问题关于网络设计语言的快速教程。 (A quick tutorial on the design language of the web.) CSS (Cascading Style Sheets) is what makes web pages look good and presentable. It’s an essential part of modern web development and a must-have skill for …

leetcode39. 组合总和(回溯)

给定一个无重复元素的数组 candidates 和一个目标数 target &#xff0c;找出 candidates 中所有可以使数字和为 target 的组合。 candidates 中的数字可以无限制重复被选取。 说明&#xff1a; 所有数字&#xff08;包括 target&#xff09;都是正整数。 解集不能包含重复的…

一脸懵逼学习基于CentOs的Hadoop集群安装与配置(三台机器跑集群)

1&#xff1a;Hadoop分布式计算平台是由Apache软件基金会开发的一个开源分布式计算平台。以Hadoop分布式文件系统&#xff08;HDFS&#xff09;和MapReduce&#xff08;Google MapReduce的开源实现&#xff09;为核心的Hadoop为用户提供了系统底层细节透明的分布式基础架构。 注…

linux批量去掉文件名前缀,linux 批量删除某个前缀文件

1. 命令 (参考&#xff1a;https://blog.csdn.net/kl28978113/article/details/80271831)find ./ -name updatesites*-* -exec rm {} \;2. 举例[rootadmin batch-create-sites]# ls2020-02-13-10-10.out logs-2020-04-07-08-00.out updatesites-2020-02-12-01-49-25.xlsx updat…

Docker - 避免启动container后运行shell脚本执行完成后docker退出container

问题 最近在使用 Dockerfile 启动容器&#xff0c;发现使用Dockerfile调用容器里面的shell&#xff0c;当shell执行完成以后&#xff0c;docker会退出容器。 分析 Docker 在执行shell的时候&#xff0c;是在后台执行的&#xff1b;因此&#xff0c;在shell执行完成以后&#xf…

css画横线箭头_用CSS绘制三角形箭头

用CSS绘制三角形箭头。使用纯CSS&#xff0c;你只需要很少的代码就可以创作出各种浏览器都兼容的三角形箭头&#xff01;CSS代码:/* create an arrow that points up */div.arrow-up {width: 0;height: 0;border-left: 5px solid transparent; /* left arrow slant */border-ri…

Jmeter参数化的理解

jmeter参数化有两种情况&#xff1a; jmeter执行的sql语句中值的参数化&#xff08;如select过滤条件&#xff09;csv data set config参数表示方式${zjhm}jmx脚本的设置属性参数化&#xff0c;方便命令行调用时修改参数&#xff08;如并发量、执行时间&#xff09;在脚本中调用…

leetcode216. 组合总和 III(回溯)

找出所有相加之和为 n 的 k 个数的组合。组合中只允许含有 1 - 9 的正整数&#xff0c;并且每种组合中不存在重复的数字。 说明&#xff1a; 所有数字都是正整数。 解集不能包含重复的组合。 示例 1: 输入: k 3, n 7 输出: [[1,2,4]] 代码 class Solution {List<List…

linux内核epub,Android底层开发技术实战详解——内核、移植和驱动(第2版)[EPUB][MOBI][AZW3][42.33MB]...

内容简介本书从底层原理开始讲起&#xff0c;结合真实的案例向读者详细介绍了Android内核、移植和驱动开发的整个流程。全书分为21章&#xff0c;依次讲解驱动移植的必要性&#xff0c; Goldfish、OMAP内核和驱动解析&#xff0c;显示系统、输入系统、振动器系统、音频系统、视…

机器学习岗位太少_太多的东西要学习,很少的时间

机器学习岗位太少by Rick West由里克韦斯特(Rick West) 太多的东西要学习&#xff0c;很少的时间 (So much to learn, so little time) 我学习&#xff0c;保持动力并实现目标的主要技巧 (My top tips for learning, staying motivated, and achieving your goals) One of the…