JavaScript's design pattern is a classic proxy pattern

  • 2021-01-02 21:45:55
  • OfStack

1. Concept of proxy pattern

Note: As the name implies, one class is used to replace another class to perform method functions. This pattern is somewhat similar to the decorative pattern, except that the proxy pattern is used to replace the client to initialize the class of the object to be represented, while the decorative pattern is implemented in the way of interface or initial decorator parameter reference.

Explanation: housing agents, agents can help sellers to sell the house to the buyer, the seller said to sell the price is ok, the buyer can also put forward their own to buy the house, the intermediary can help deal with the intermediate link. Finally, a sale is made. An intermediary can buy and sell many houses at the same time, and can act as a rental agent.

2. Role of the agency model and matters needing attention

Role of model:

1. Remote proxy (one object acts as a local proxy for objects in different Spaces)

2. Virtual agent (to create expensive objects as needed, such as rendering web pages with placeholders instead of real images)

3. Security agent (control the access rights of verified objects)

4. Intelligent guidance (calling the object proxy to handle another thing like garbage collection)


1. Don't abuse the agent, sometimes it just adds complexity to the code

3. Code and practice summary of proxy mode

<!DOCTYPE html>
<head lang="en">
<meta charset="UTF-8">
// The proxy pattern requires 3 party 
//1. buyers 
function maijia(){ = " Xiao Ming "; = "30 wan ";
//2. The mediation 
function zhongjie(){
zhongjie.prototype.maifang = function(){
//new fongdong(new maijia()).maifang("20 wan ");
new fongdong(new maijia()).maifang("20 wan ");
//3. The seller 
function fongdong(maijia){
this.maijia_name =;
this.maijia_money =;
this.maifang = function(money){
// alert(" Received from [ "+this.maijia_name+" 】 "+money+" The yuan ");
alert(" Received from [ "+this.maijia_name+" 】 "+this.maijia_money+" The yuan ");
(new zhongjie()).maifang();
// A2B
function A(){ = "20RMB";
function to(){
if(!(this instanceof to)){
return new to;
to.prototype.maifang = function(){
var a = new A();
new B().maifang(;
function B(){
this.maifang = function(money){
alert(" Received the money "+money);
(new to()).maifang();

Related articles: