Understanding Javascript Proxy

  Agent, es6, javascript

About Proxy

Proxy is a very common concept in the computer field. Chinese is usually translated as proxy. Proxy is generally used to describe someone or something acting on behalf of others. Common concepts include Proxy Server, Reverse Proxy, Proxy Pattern, etc.

To understand Proxy, let’s ask ourselves a few questions:

  1. What is Proxy?

    As mentioned above, an agent is someone or something acting on behalf of others.

  2. Why do you need a Proxy?

    There are several possibilities. 1. The subject does not want to be interviewed directly, just like he needs to contact his agent before looking for a star to make a movie. 2. The person to be represented needs to find someone to help hi m do some work because of his insufficient ability, for example, he needs to find a lawyer to engage in a lawsuit. Therefore, Proxy can play at least two roles: access control and additional functions.

Understanding the above two questions makes learning Javascript Proxy much easier.

Proxy for ES6

Proxy also appears in ES6. Similar to other proxies, Proxy in ES6 is also used to Proxy something. Similarly, we need to understand several problems:

  1. Proxy proxy what?

    Proxy Object (This is nonsense, everything in javascript is Object)

  2. What does Proxy proxy Object do?

    Control and modify the basic behavior of Object

  3. What are the basic behaviors of Object?

    Such as attribute call, attribute assignment, attribute deletion, method call, etc

  4. Why do you want to control and modify the basic behavior of Object?

    As discussed earlier, access control and additional functions are implemented.

Proxy usage

Basic grammar

Create a proxy:

const p = new Proxy(target, handler);

target: is a proxy object, which can be an object, an array, a method, a constructor class, or even another proxy. In short, it can be any JavaScript object.

handler: An object whose attributes are various controls or modificationstargetMethods of basic behavior;

Example

For example, if the user does not set an avatar, the default avatar will be returned, which can be written as follows:

const user = { name: 'bruce' };
 const userProxy = new Proxy(user, {
 get: (obj, prop) => {
 if (prop === 'avatar') {
 if (!  obj.avatar) {
 return 'https://avatar-static.segmentfault.com/100/035/1000355095-5b3c339ebdbe1_big64';
 }
 }
 return obj[prop];
 }
 });
 
 console.log(userProxy.avatar);  // https://avatar-static···

Or we can implement alert to wrap and display multiple messages:

const myAlert = new Proxy(alert, {
 apply: (target, thisArg, argumentsList) => {
 const msg = argumentsList.join('\n');
 target(msg);
 }
 });
 
 myAlert('haha', 'lala');

image

React source code also has the application of proxy, which is used to uniformly manage event:

/** Proxying after everything set on SyntheticEvent
 * to resolve Proxy issue on some WebKit browsers
 * in which some Event properties are set to undefined (GH#10010)
 */
 {
 var isProxySupported = typeof Proxy === 'function' &&
 //  https://github.com/facebook/react/issues/12011
 !  Object.isSealed(new Proxy({}, {}));
 
 if (isProxySupported) {
 /*eslint-disable no-func-assign */
 SyntheticEvent = new Proxy(SyntheticEvent, {
 construct: function (target, args) {
 return this.apply(target, Object.create(target.prototype), args);
 },
 apply: function (constructor, that, args) {
 return new Proxy(constructor.apply(that, args), {
 set: function (target, prop, value) {
 if (prop !  == 'isPersistent' && !  target.constructor.Interface.hasOwnProperty(prop) && shouldBeReleasedProperties.indexOf(prop) === -1) {
 !  (didWarnForAddedNewProperty || target.isPersistent()) ?   warning_1(false, "This synthetic event is reused for performance reasons. If you're " + "seeing this,   you're adding a new property in the synthetic event object. " + 'The property is never released. See ' + 'https://fb.me/react-event-pooling for more information.') : void 0;
 didWarnForAddedNewProperty = true;
 }
 target[prop] = value;
 return true;
 }
 });
 }
 });
 /*eslint-enable no-func-assign */
 }
 }

Thank you for reading. In addition, I’m here to help my friends raise funds for love. I hope everyone can give some love. My friend’s mother is suffering from rectal cancer. She is currently receiving treatment in Beijing Armed Police General Hospital. Please leave a message and leave your contact information. Thank you in the future!

clipboard.png