What is Proxy
First of all, we need to understand what Proxy
means. When translated, this word means acting.
It can be understood that there is a very popular star who has opened a Weibo account. This account is very active, replying to fans, giving likes everywhere, etc., but it may not really be maintained by him. .
But there is another person or team behind the operation, we can call them agents, because the Weibo they publish represents the meaning of the star himself.
P.S. Forcibly give an example, because I am not chasing stars, I just guess that there may be such an operation team
This is substituted into JavaScript
, It can be understood as a proxy operation on object
or function
.
Proxy in JavaScript
Proxy is a new API provided in ES6, which can be used to define custom behaviors for various basic operations of objects (discussed in the document It's called traps, I think it can be understood as a hook for various behaviors of objects), you can do a lot of interesting things with it, and it will become very effective when we need to control the behavior of some objects.
Proxy syntax
Creating an instance of Proxy
requires passing in two parameters
-
target
The object to be proxied can be anobject
orfunction
-
handlers
Various operating behaviors of the proxy object Processing
let target = {} let handlers = {} // do nothing let proxy = new Proxy(target, handlers) proxy.a = 123 console.log(target.a) // 123
When the second parameter is an empty object, it can basically be understood as a shallow copy of the first parameter
(Proxy must be a shallow copy , if it is a deep copy, the meaning of the agent will be lost)
Traps (agent for various behaviors)
Just like the sample code above, If the corresponding trap
is not defined, it will not have any effect, which is equivalent to directly operating target
.
When we write a certain trap
, when we perform the corresponding action, our callback function will be triggered, and we will control the behavior of the proxy object.
The two most commonly used trap
should be get
and set
.
Early YearsJavaScript
There is a way to set a certain property when defining an objectgetter
、setter
:
let obj = { _age: 18, get age () { return `I'm ${this._age} years old` }, set age (val) { this._age = Number(val) } } console.log(obj.age) // I'm 18 years old obj.age = 19 console.log(obj.age) // I'm 19 years old
Like This code describes the same, we set a property _age
, and then set a get age
and set age
.
Then we can directly call obj.age
to get a return value, or assign it.
There are several disadvantages to doing this:
- For each attribute to be proxied, the corresponding
getter
andsetter
must be written. - There must also be a
key
that stores the real value (if we call this.age directly in the getter, a stack overflow will occur, because whenever we call this .age will trigger getter when taking value).
Proxy
solves these two problems very well:
let target = { age: 18, name: 'Niko Bellic' } let handlers = { get (target, property) { return `${property}: ${target[property]}` }, set (target, property, value) { target[property] = value } } let proxy = new Proxy(target, handlers) proxy.age = 19 console.log(target.age, proxy.age) // 19, age : 19 console.log(target.name, proxy.name) // Niko Bellic, name: Niko Bellic
We create get
, set
Two trap
to manage all operations uniformly. You can see that while modifying proxy
, the content of target
is also modified, and we have # The behavior of ##proxy has been treated with some special processing.
key to store the real value, because we operate the
target object inside
trap, and Not a
proxy object.
What to do with Proxy
Because after usingProxy, the behavior of the object is basically controllable, so we It can be used to do some things that were more complicated to implement before.
undefined has always been a painful process. If we use
Proxy can be well compatible with this situation.
(() => { let target = {} let handlers = { get: (target, property) => { target[property] = (property in target) ? target[property] : {} if (typeof target[property] === 'object') { return new Proxy(target[property], handlers) } return target[property] } } let proxy = new Proxy(target, handlers) console.log('z' in proxy.x.y) // false (其实这一步已经针对`target`创建了一个x.y的属性) proxy.x.y.z = 'hello' console.log('z' in proxy.x.y) // true console.log(target.x.y.z) // hello })()We proxy
get and perform logical processing inside it. If we want to perform
get, the value comes from a non-existent
key , then we will create a corresponding
key in
target, and then return a proxy object for this
key.
can not get xxx from undefinedBut this will have a small disadvantage, that is, if you really want to judge this Whether
key exists can only be judged through the
in operator, and cannot be judged directly through
get.
普通函数与构造函数的兼容处理
如果我们提供了一个Class
对象给其他人,或者说一个ES5
版本的构造函数。
如果没有使用new
关键字来调用的话,Class
对象会直接抛出异常,而ES5
中的构造函数this
指向则会变为调用函数时的作用域。
我们可以使用apply
这个trap
来兼容这种情况:
class Test { constructor (a, b) { console.log('constructor', a, b) } } // Test(1, 2) // throw an error let proxyClass = new Proxy(Test, { apply (target, thisArg, argumentsList) { // 如果想要禁止使用非new的方式来调用函数,直接抛出异常即可 // throw new Error(`Function ${target.name} cannot be invoked without 'new'`) return new (target.bind(thisArg, ...argumentsList))() } }) proxyClass(1, 2) // constructor 1 2
我们使用了apply
来代理一些行为,在函数调用时会被触发,因为我们明确的知道,代理的是一个Class
或构造函数,所以我们直接在apply
中使用new
关键字来调用被代理的函数。
以及如果我们想要对函数进行限制,禁止使用new
关键字来调用,可以用另一个trap
:construct
function add (a, b) { return a + b } let proxy = new Proxy(add, { construct (target, argumentsList, newTarget) { throw new Error(`Function ${target.name} cannot be invoked with 'new'`) } }) proxy(1, 2) // 3 new proxy(1, 2) // throw an error
用Proxy来包装fetch
在前端发送请求,我们现在经常用到的应该就是fetch
了,一个原生提供的API。
我们可以用Proxy
来包装它,使其变得更易用。
let handlers = { get (target, property) { if (!target.init) { // 初始化对象 ['GET', 'POST'].forEach(method => { target[method] = (url, params = {}) => { return fetch(url, { headers: { 'content-type': 'application/json' }, mode: 'cors', credentials: 'same-origin', method, ...params }).then(response => response.json()) } }) } return target[property] } } let API = new Proxy({}, handlers) await API.GET('XXX') await API.POST('XXX', { body: JSON.stringify({name: 1}) })
对GET
、POST
进行了一层封装,可以直接通过.GET
这种方式来调用,并设置一些通用的参数。
实现一个简易的断言工具
写过测试的各位童鞋,应该都会知道断言这个东西console.assert
就是一个断言工具,接受两个参数,如果第一个为false
,则会将第二个参数作为Error message
抛出。
我们可以使用Proxy
来做一个直接赋值就能实现断言的工具。
let assert = new Proxy({}, { set (target, message, value) { if (!value) console.error(message) } }) assert['Isn\'t true'] = false // Error: Isn't true assert['Less than 18'] = 18 >= 19 // Error: Less than 18
统计函数调用次数
在做服务端时,我们可以用Proxy
代理一些函数,来统计一段时间内调用的次数。
在后期做性能分析时可能会能够用上:
function orginFunction () {} let proxyFunction = new Proxy(orginFunction, { apply (target, thisArg. argumentsList) { log(XXX) return target.apply(thisArg, argumentsList) } })
全部的traps
这里列出了handlers
所有可以定义的行为 (traps):
具体的可以查看MDN-Proxy
里边同样有一些例子
traps | description |
---|---|
get | 获取某个key 值 |
set | 设置某个key 值 |
has | 使用in 操作符判断某个key 是否存在 |
apply | 函数调用,仅在代理对象为function 时有效 |
ownKeys | 获取目标对象所有的key
|
construct | 函数通过实例化调用,仅在代理对象为function 时有效 |
isExtensible | 判断对象是否可扩展,Object.isExtensible 的代理 |
deleteProperty | 删除一个property
|
defineProperty | 定义一个新的property
|
getPrototypeOf | 获取原型对象 |
setPrototypeOf | 设置原型对象 |
preventExtensions | 设置对象为不可扩展 |
getOwnPropertyDescriptor | 获取一个自有属性 (不会去原型链查找) 的属性描述 |
更多编程相关知识,请访问:编程学习网站!!
The above is the detailed content of Detailed explanation of Proxy in JavaScript. For more information, please follow other related articles on the PHP Chinese website!

去掉重复并排序的方法:1、使用“Array.from(new Set(arr))”或者“[…new Set(arr)]”语句,去掉数组中的重复元素,返回去重后的新数组;2、利用sort()对去重数组进行排序,语法“去重数组.sort()”。

本篇文章给大家带来了关于JavaScript的相关知识,其中主要介绍了关于Symbol类型、隐藏属性及全局注册表的相关问题,包括了Symbol类型的描述、Symbol不会隐式转字符串等问题,下面一起来看一下,希望对大家有帮助。

怎么制作文字轮播与图片轮播?大家第一想到的是不是利用js,其实利用纯CSS也能实现文字轮播与图片轮播,下面来看看实现方法,希望对大家有所帮助!

本篇文章给大家带来了关于JavaScript的相关知识,其中主要介绍了关于对象的构造函数和new操作符,构造函数是所有对象的成员方法中,最早被调用的那个,下面一起来看一下吧,希望对大家有帮助。

方法:1、利用“点击元素对象.unbind("click");”方法,该方法可以移除被选元素的事件处理程序;2、利用“点击元素对象.off("click");”方法,该方法可以移除通过on()方法添加的事件处理程序。

本篇文章给大家带来了关于JavaScript的相关知识,其中主要介绍了关于面向对象的相关问题,包括了属性描述符、数据描述符、存取描述符等等内容,下面一起来看一下,希望对大家有帮助。

foreach不是es6的方法。foreach是es3中一个遍历数组的方法,可以调用数组的每个元素,并将元素传给回调函数进行处理,语法“array.forEach(function(当前元素,索引,数组){...})”;该方法不处理空数组。

本篇文章给大家带来了关于JavaScript的相关知识,其中主要介绍了关于BOM操作的相关问题,包括了window对象的常见事件、JavaScript执行机制等等相关内容,下面一起来看一下,希望对大家有帮助。


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

Notepad++7.3.1
Easy-to-use and free code editor

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.