What is a JavaScript proxy? Introduction to javascript proxy
本篇文章给大家带来的内容是关于JavaScript代理是什么?javascript代理的介绍,有一定的参考价值,有需要的朋友可以参考一下,希望对你有所帮助。
前言
什么是代理?
上小学的时候,李小红来你家叫你出去玩,第一个回应的不是你自己,是你妈:“王小明在家写作业,今天不出去!”
上中学的时候,赵二虎带着小弟们放学在校门口等着揍你,走在前面的不是你自己,是二虎他爸:“考试没及格还学会装黑社会了!”拎起二虎就是一顿胖揍。
上了大学,躺在宿舍里的床上,好饿。出门买饭并交代好不要葱蒜多放辣最后还直接端到床上的不是你自己,是快递小哥。
这些都是代理。
什么是 JavaScript 代理?
用官方的洋文来说,是 Proxy:
The Proxy object is used to define custom behavior for fundamental operations (e.g. property lookup, assignment, enumeration, function invocation, etc).
通过 Proxy 我们可以拦截并改变一个对象的几乎所有的根本操作,包括但不限于属性查找、赋值、枚举、函数调用等等。
在生活中,通过代理我们可以自动屏蔽小红的邀请、自动赶走二虎的威胁、自动买好干净的饭端到床上。在 JavaScript 世界里,代理也可以帮你做类似的事情,接下来让我们一起琢磨一番。
初识代理:Hello World
以小学经历为例子,心里是喜欢小红的,于是我们定义:
const me = { name: '小明', like: '小红' }
这个时候如果调用 console.log(me.like)
,结果必然是 小红
。然而生活并不是这样,作为一个未成年人,总是有各种的代理人围绕在你身边,比如这样:
const meWithProxy = new Proxy(me, { get(target, prop) { if (prop === 'like') { return '学习'; } return target[prop]; } });
这个时候如果调用 console.log(me.like)
依然是 小红
,因为真心不会说谎。但当我们调用 console.log(meWithProxy.like)
的时候,就会可耻的输出 学习
,告诉大家说我们喜欢的是 学习
。
小试牛刀:不要停止我的音乐
刚才我们简单了解了代理能够拦截对象属性的获取,可以隐藏真实的属性值而返回代理想要返回的结果,那么对于对象属性的赋值呢?让我们一起来看看。
假设你正在听音乐:
const me = { name: '小明', musicPlaying: true }
此时如果我们执行 me.musicPlaying = false
这样就轻而易举地停止了你的音乐,那么如果我们挂上代理人:
const meWithProxy = new Proxy(me, { set(target, prop, value) { if (prop === 'musicPlaying' && value !== true) { throw Error('任何妄图停止音乐的行为都是耍流氓!'); } target[prop] = value; } });
这时候如果我们执行 me.musicPlaying = false
,就会被毫不留情地掀了桌子:
> meWithProxy.musicPlaying = false Error: 任何妄图停止音乐的行为都是耍流氓! at Object.set (repl:4:13) >
释放魔法:封装全宇宙所有 RESTful API
现在我们已经知道通过 Proxy 可以拦截属性的读写操作,那然后呢?没什么用?
仅仅是拦截属性的读写操作,的确没有太大的发挥空间,或许可以方便的做一些属性赋值校验工作等等。但是,或许你还没有意识到一个惊人的秘密:Proxy 在拦截属性读写操作时,并不在乎属性是否真的存在!
那么,也就是说:利用 Proxy,我们可以拦截并不存在的属性的读取。
再进一步思考:利用 Proxy,我们可以在属性读取的那一瞬间,动态构造返回结果。
然而,属性并不局限于字符串、布尔值,属性可以是对象、函数、任何东西。
至此,你想到了什么?
没想到?不要紧!根据刚才的分析,让我们一起通过下面 17 行代码,来封装全宇宙所有的 RESTful API !
import axios from 'axios'; const api = new Proxy({}, { get(target, prop) { const method = /^[a-z]+/.exec(prop)[0]; const path = '/' + prop .substring(method.length) .replace(/([a-z])([A-Z])/g, '$1/$2') .replace(/\$/g, '/$/') .toLowerCase(); return (...args) => { // args.shift()); const options = args.shift() || {}; console.log('Requesting: ', method, url, options); return axios({ method, url, ...options }); } } });
定义了 api 这个代理之后,我们就可以像下面这样调用:
api.get() // GET / api.getUsers() // 获取所有用户 // GET /users api.getUsers$Books(42) // 获取 ID 为 42 的用户的所有书籍 // GET /users/42/books api.getUsers$Books(42, { params: { page: 2 } }) // 获取 ID 为 42 的用户的所有书籍的第二页 // GET /users/42/books?page=2 api.postUsers({ data: { name: '小明' } }) // 创建名字为 小明 的用户 // POST /users Payload { name: '小明' }
以上所有的函数都在你调用的那一瞬间,通过代理人的魔法之手动态生成,供我们随意取用。
简洁、优雅,哇~ 真是太棒啦!
终极魔幻:通读代理人的魔法秘笈
到此,我们仅仅使用 Proxy 改造了对象的属性获取、赋值操作,而对于 Proxy 来说,只是冰山一角。
Proxy 的基本语法如下:
new Proxy(target, handler)
其中 target
是即将被代理的对象(比如:想要出门找小红玩耍的 me
),handler
就是代理的魔法之手,用来拦截、改造 target
的行为。
对于 handler
对象,我们刚才仅仅用到了 get
、set
函数,而实际上一共有 13 种可代理的操作:
-
handler.getPrototypeOf()
在读取代理对象的原型时触发该操作,比如在执行 Object.getPrototypeOf(proxy) 时。
-
handler.setPrototypeOf()
在设置代理对象的原型时触发该操作,比如在执行 Object.setPrototypeOf(proxy, null) 时。
-
handler.isExtensible()
This operation is triggered when determining whether a proxy object is extensible, such as when executing Object.isExtensible(proxy).
-
handler.preventExtensions()
This operation is triggered when making a proxy object non-extensible, such as when executing Object.preventExtensions(proxy).
-
handler.getOwnPropertyDescriptor()
This operation is triggered when obtaining the property description of a property of the proxy object, such as when executing Object.getOwnPropertyDescriptor(proxy, "foo" ) hour.
-
handler.defineProperty()
This operation is triggered when defining the property description of a property of the proxy object, such as when executing Object.defineProperty(proxy, "foo ", {}) hour.
-
handler.has()
This operation is triggered when determining whether the proxy object has a certain attribute, such as when executing "foo" in proxy.
-
handler.get()
This operation is triggered when reading a certain property of the proxy object, such as when executing proxy.foo.
-
handler.set()
This operation is triggered when assigning a value to a property of the proxy object, such as when executing proxy.foo = 1.
-
handler.deleteProperty()
This operation is triggered when a property of the proxy object is deleted, such as when executing delete proxy.foo.
-
handler.ownKeys()
This operation is triggered when all property keys of the proxy object are obtained, such as when executing Object.getOwnPropertyNames(proxy).
-
handler.apply()
This operation is triggered when calling a proxy object whose target object is a function, such as when executing proxy().
-
handler.construct()
This operation is triggered when constructing an instance of a proxy object whose target object is the constructor, such as when executing new proxy().
For the above 13 agentable operations, readers need to study and practice on their own before embarking on the ultimate magical journey.
The above is the detailed content of What is a JavaScript proxy? Introduction to javascript proxy. For more information, please follow other related articles on the PHP Chinese website!

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing

This article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base

JavaScript is the core language of modern web development and is widely used for its diversity and flexibility. 1) Front-end development: build dynamic web pages and single-page applications through DOM operations and modern frameworks (such as React, Vue.js, Angular). 2) Server-side development: Node.js uses a non-blocking I/O model to handle high concurrency and real-time applications. 3) Mobile and desktop application development: cross-platform development is realized through ReactNative and Electron to improve development efficiency.

The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.

JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.


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

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment