Advantages and usage scenarios of JS Proxy
People who drive cars often don’t understand the structure of the car, but a deep understanding of the structure of the car may have an even more powerful effect
Preface
As the news of vue3.x
increases, so does the discussion of proxy
. Compared with Object.defineProperty
, what are the differences, advantages and applications of proxy
? This article will briefly introduce
Object.defineProperty
Before talking about proxy
, let’s review Object.defineProperty
. As we all know, vue2.x
and previous versions use Object.defineProperty
to achieve two-way binding of data. As for how to bind it? Let’s simply implement it
function observer(obj) { if (typeof obj === 'object') { for (let key in obj) { defineReactive(obj, key, obj[key]) } } } function defineReactive(obj, key, value) { //针对value是对象,递归检测 observer(value) //劫持对象的key Object.defineProperty(obj, key, { get() { console.log('获取:' + key) return value }, set(val) { //针对所设置的val是对象 observer(val) console.log(key + "-数据改变了") value = val } }) } let obj = { name: '守候', flag: { book: { name: 'js', page: 325 }, interest: ['火锅', '旅游'], } } observer(obj)
Execute it in the browserconsole
, it seems to run normally
But in fact,Object.defineProperty
The problems are as follows
Problems 1. Deleting or adding object properties cannot be monitored
For example, adding an attributegender
, because during execution observer(obj)
does not have this attribute, so it cannot be monitored. Deleted attributes cannot be monitored when
is added.
vue
needs to be operated using$set
.$set
Object.defineProperty
is also used internally for operations
Object.defineProperty is used to hijack the properties of the object. If the object level traversed is relatively deep, it will take a long time and may even cause performance problems
proxy
Forproxy, the description on mdn is: Object is used to define custom behaviors for basic operations (such as attribute lookup, assignment, enumeration, function call, etc.)
proxy is easier to use than
Object.defineProperty, and it is much simpler. In fact That's it. Let's use proxy to rewrite the above code and try it
function observerProxy(obj) { let handler = { get(target, key, receiver) { console.log('获取:' + key) // 如果是对象,就递归添加 proxy 拦截 if (typeof target[key] === 'object' && target[key] !== null) { return new Proxy(target[key], handler) } return Reflect.get(target, key, receiver) }, set(target, key, value, receiver) { console.log(key + "-数据改变了") return Reflect.set(target, key, value, receiver) } } return new Proxy(obj, handler) } let obj = { name: '守候', flag: { book: { name: 'js', page: 325 }, interest: ['火锅', '旅游'], } } let objTest = observerProxy(obj)
##And, it can do
Things that cannot be done, such as adding an attribute gender
, can monitor the
operation array, and can also monitor the
Finally, knock on the blackboard and briefly summarize the difference between the two
1.
Object.defineProperty What is intercepted is the property of the object, which will change the original object. proxy
intercepts the entire object and generates a new object through new without changing the original object. 2.
In addition to the above get and set, there are 11 other interception methods. There are many ways to choose Proxy, and you can also monitor some operations that Object.defineProperty
cannot, such as monitoring arrays, monitoring the addition and deletion of object properties, etc.
Regarding the usage scenarios of
proxy, due to space limitations, I will simply list a few here, and more can be moved Follow my github notes or mdn. Seeing this, I already know the difference between the two and the advantages of
. But in development, what scenarios can proxy
be used? Here are some situations that may be encountered
When using
splice(-1), slice(-1)
and other APIs, when a negative number is entered, the last item of the array will be located, but on a normal array , and negative numbers cannot be used. [1,2,3][-1]
This code cannot output 3. To make the above code output 3, you can also use proxy
. <div class="code" style="position:relative; padding:0px; margin:0px;"><pre class="brush:php;toolbar:false"><br></pre><div class="contentsignin">Copy after login</div></div>
表单校验
在对表单的值进行改动的时候,可以在 set
里面进行拦截,判断值是否合法
let ecValidate = { set(target, key, value, receiver) { if (key === 'age') { //如果值小于0,或者不是正整数 if (value < 0 || !Number.isInteger(value)) { throw new TypeError('请输入正确的年龄'); } } return Reflect.set(target, key, value, receiver) } } let obj = new Proxy({ age: 18 }, ecValidate) obj.age = 16obj.age = '少年'
增加附加属性
比如有一个需求,保证用户输入正确身份证号码之后,把出生年月,籍贯,性别都添加进用户信息里面
众所周知,身份证号码第一和第二位代表所在省(自治区,直辖市,特别行政区),第三和第四位代表所在市(地级市、自治州、盟及国家直辖市所属市辖区和县的汇总码)。第七至第十四位是出生年月日。低17位代表性别,男单女双。
const PROVINCE_NUMBER = { 44 : '广东省', 46 : '海南省' } const CITY_NUMBER = { 4401 : '广州市', 4601 : '海口市' } let ecCardNumber = { set(target, key, value, receiver) { if (key === 'cardNumber') { Reflect.set(target, 'hometown', PROVINCE_NUMBER[value.substr(0, 2)] + CITY_NUMBER[value.substr(0, 4)], receiver) Reflect.set(target, 'date', value.substr(6, 8), receiver) Reflect.set(target, 'gender', value.substr( - 2, 1) % 2 === 1 ? '男': '女', receiver) } return Reflect.set(target, key, value, receiver) } } let obj = new Proxy({ cardNumber: '' }, ecCardNumber)
数据格式化
比如有一个需求,需要传时间戳给到后端,但是前端拿到的是一个时间字符串,这个也可以用 proxy
进行拦截,当得到时间字符串之后,可以自动加上时间戳。
let ecArrayProxy = { get(target, key, receiver) { let _index = key < 0 ? target.length + Number(key) : key return Reflect.get(target, _index, receiver) } } let arr = new Proxy([1, 2, 3], ecArrayProxy)
<br>
推荐教程:《JS教程》 <br>
The above is the detailed content of Advantages and usage scenarios of JS Proxy. For more information, please follow other related articles on the PHP Chinese website!

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

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

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

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

Hot Topics



Using JSON.parse() string to object is the safest and most efficient: make sure that strings comply with JSON specifications and avoid common errors. Use try...catch to handle exceptions to improve code robustness. Avoid using the eval() method, which has security risks. For huge JSON strings, chunked parsing or asynchronous parsing can be considered for optimizing performance.

Implement marquee/text scrolling effects in Vue, using CSS animations or third-party libraries. This article introduces how to use CSS animation: create scroll text and wrap text with <div>. Define CSS animations and set overflow: hidden, width, and animation. Define keyframes, set transform: translateX() at the beginning and end of the animation. Adjust animation properties such as duration, scroll speed, and direction.

export default is used to export Vue components and allow other modules to access. import is used to import components from other modules, which can import a single or multiple components.

The data structure must be clearly defined when the Vue and Element-UI cascaded drop-down boxes pass the props, and the direct assignment of static data is supported. If data is dynamically obtained, it is recommended to assign values within the life cycle hook and handle asynchronous situations. For non-standard data structures, defaultProps or convert data formats need to be modified. Keep the code simple and easy to understand with meaningful variable names and comments. To optimize performance, virtual scrolling or lazy loading techniques can be used.

Vue component passing values is a mechanism for passing data and information between components. It can be implemented through properties (props) or events: Props: Declare the data to be received in the component and pass the data in the parent component. Events: Use the $emit method to trigger an event and listen to it in the parent component using the v-on directive.

In Vue.js, lazy loading allows components or resources to be loaded dynamically as needed, reducing initial page loading time and improving performance. The specific implementation method includes using <keep-alive> and <component is> components. It should be noted that lazy loading can cause FOUC (splash screen) issues and should be used only for components that need lazy loading to avoid unnecessary performance overhead.

When converting strings to objects in Vue.js, JSON.parse() is preferred for standard JSON strings. For non-standard JSON strings, the string can be processed by using regular expressions and reduce methods according to the format or decoded URL-encoded. Select the appropriate method according to the string format and pay attention to security and encoding issues to avoid bugs.

The use of Axios request method in Vue.js requires following these principles: GET: Obtain resources, do not modify data. POST: Create or submit data, add or modify data. PUT: Update or replace existing resources. DELETE: Delete the resource from the server.
