search
HomeWeb Front-endJS TutorialDetailed explanation of Proxy use cases

Detailed explanation of Proxy use cases

May 25, 2018 am 11:57 AM
proxyuseDetailed explanation

This time I will bring you a detailed explanation of Proxy use cases, what are the precautions when using Proxy, the following is a practical case, let's take a look.

What is Proxy

First of all, we need to understand what Proxy means. When translated, this word is proxy.
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<a href="http://www.php.cn/wiki/48.html" target="_blank">JavaScript</a> Among them, 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
(referred to 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, when we need to control the behavior of some objects will become very effective.

Proxy syntax

Creating an instance of Proxy requires passing in two parameters

  1. target The object to be proxied can be an object or a function

  2. handlers for the proxy object. This kind of operation behavior 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 proxy will be lost)

Traps (Proxies 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 YearsJavaScriptThere is a way to set a certain property when defining an objectgettersetter

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

Just like this code As described, we set an attribute _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:

  1. For each attribute to be proxied, the corresponding getter and setter must be written.

  2. There must also be a key that stores the real value (if we call this directly in getter. age will cause stack overflow, because whenever this.age is called to obtain a value, getter) will be triggered.

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, settwo trap to manage all operations uniformly, you can see that while modifying proxy, the content of target is also modified, and We have made some special handling of the behavior of proxy.
And we don’t need to use an additional key to store the real value, because we are operating on the target object inside trap, not proxyObject.

What to do with Proxy

Because after using Proxy, the behavior of the object is basically controllable, so we can use it to do some things before Something more complicated to implement.
A few simple applicable scenarios are listed below.

解决对象属性为undefined的问题

在一些层级比较深的对象属性获取中,如何处理undefined一直是一个痛苦的过程,如果我们用Proxy可以很好的兼容这种情况。

(() => {
  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
})()

我们代理了get,并在里边进行逻辑处理,如果我们要进行get的值来自一个不存在的key,则我们会在target中创建对应个这个key,然后返回一个针对这个key的代理对象。  
这样就能够保证我们的取值操作一定不会抛出can not get xxx from undefined  
但是这会有一个小缺点,就是如果你确实要判断这个key是否存在只能够通过in操作符来判断,而不能够直接通过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})
})

GETPOST进行了一层封装,可以直接通过.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)

For details, you can view MDN-Proxy
There are also some examples in it
##isExtensible Determine whether the object is extensible, proxy of deletePropertyDelete a definePropertyDefine a new getPrototypeOfGet the prototype objectsetPrototypeOfSet the prototype objectpreventExtensionsSet the object as non-extensiblegetOwnPropertyDescriptorGet an own property
traps description
get Get a key value
set Set a keyValue
has Use the in operator to determine whether a key exists
apply Function call, only valid when the proxy object is function
ownKeys Get all the key
construct of the target object. The function is called by instantiation, only when the proxy object is function# Valid when
Object.isExtensible
property
property
(will not search the prototype chain ) Attribute description
I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to other related articles on the php Chinese website!

Recommended reading:

Summary of using JS methods in HTML

Summary of using CSS selectors

The above is the detailed content of Detailed explanation of Proxy use cases. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
JavaScript in Action: Real-World Examples and ProjectsJavaScript in Action: Real-World Examples and ProjectsApr 19, 2025 am 12:13 AM

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

JavaScript and the Web: Core Functionality and Use CasesJavaScript and the Web: Core Functionality and Use CasesApr 18, 2025 am 12:19 AM

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding the JavaScript Engine: Implementation DetailsUnderstanding the JavaScript Engine: Implementation DetailsApr 17, 2025 am 12:05 AM

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python vs. JavaScript: The Learning Curve and Ease of UsePython vs. JavaScript: The Learning Curve and Ease of UseApr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python vs. JavaScript: Community, Libraries, and ResourcesPython vs. JavaScript: Community, Libraries, and ResourcesApr 15, 2025 am 12:16 AM

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

From C/C   to JavaScript: How It All WorksFrom C/C to JavaScript: How It All WorksApr 14, 2025 am 12:05 AM

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.

JavaScript Engines: Comparing ImplementationsJavaScript Engines: Comparing ImplementationsApr 13, 2025 am 12:05 AM

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.

Beyond the Browser: JavaScript in the Real WorldBeyond the Browser: JavaScript in the Real WorldApr 12, 2025 am 12:06 AM

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.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Tools

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

MinGW - Minimalist GNU for Windows

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.