Pay attention to “songbao write code”, selected good articles, a question of the day

Saucxs | songEagle

One, foreword

The flag just established on December 23, 2020.One question of the day, the topic type is not limited, can be: algorithm questions, interview questions, elaboration questions and so on.

Q: What is your understanding of ES6 proxy

A question of the Day

  • Interviewer: What is the difference between “for in” and “for of”?

  • 6. How can Async/Await Async/Await Async?

  • How does VUE data binding work?

  • Question 4: How to find repetitive elements in a scientific and efficient way?

  • 3. “Question of the Day” The interviewer asks you what you think of Promise?

  • In ES6, why do we use Symbol?

  • 1. “How does an interview question trigger deep soul searching?”

What is Proxy?

Proxy is a new feature in ES6. It can be understood as a Proxy (that is, it acts as a Proxy for certain operations).

Proxy objects are used to define or modify user-defined behaviors of certain operations. You can rewrite external access before the target object is accessed.

1. Proxy definition

var proxy = new Proxy(target, handler)
Copy the code

New Proxy() generates a Proxy instance

  • Target: indicates the target object
  • Handler: An object whose properties are functions that define the behavior of the agent when an operation is performed.

Note: To intercept, you must operate on the Proxy instance, not the target object.

Proxy intercepts GET and set operations

Let’s take a look at proxy intercepting get and set operations as follows:

let handler = { get: function(target, key, receiver) { console.log(`getter ${key}! `) return Reflect.get(target, key, receiver) }, set: function(target, key, value, receiver) { console.log(`setter ${key}=${value}`) return Reflect.set(target, key, value, receiver) } } var obj = new Proxy({}, handler) obj.a = 1 // setter a=1 obj.b = undefined // setter b=undefined console.log(obj.a, obj.b) // getter a! // getter b! // 1 undefined console.log('c' in obj, obj.c) // getter c! // false undefinedCopy the code

Proxy overrides the component’s original behavior

Let’s take a look at the following example code:

let handler = { get: function(target, key, receiver) { return 1 }, set: function (target, key, value, receiver) { console.log(`setting ${key}! `); return Reflect.set(target, key, value, receiver); } } var obj = new Proxy({}, handler) obj.a = 5 // setting 5! console.log(obj.a); / / 1Copy the code

As you can see from the code above, the Proxy not only intercepts the behavior, but overwrites the component’s original behavior with its own defined behavior.

If handler = {}, the Proxy is not doing any interception, and accessing the Proxy instance is equivalent to accessing the target target object.

Proxy Handle method

  • 1. Get (Target, key, receiver) : intercepts reading of target attributes
  • 2. Set (Target, key, value, receiver) : Intercepts the setting of target attributes
  • Has (target, key) : intercepts the key in proxy operation and returns whether it exists (Boolean)
  • 4, deleteProperty(target, key) : intercepts delete proxy[key] operations and returns results (Boolean)
  • 5, ownKeys (target) : interception Object. GetOwnPropertyName (proxy), Object. GetOwnPropertySymbols (proxy), the Object. The keys (proxy), for… In circulation. And returns an array of all the target object’s own property names. Note: The return array of object.keys () contains only the traversable properties of the target Object itself
  • 6, getOwnPropertyDescriptor (target, key) : interception Object. GetOwnPropertyDescriptor (proxy, key), and returns the attributes describe objects
  • DefineProperty (target, key, desc) Intercepts Object.defineProperty(proxy, key, desc) and Object.defineProperties(proxy, descs), returning a Boolean value
  • 8, preventExtensions(target) : Intercept object. preventExtensions(proxy), return a Boolean
  • GetPrototypeOf (target) : Intercepts object.getProtoTypeof (proxy) and returns an Object
  • IsExtensible (target) : Intercepts Object. IsExtensible (proxy), returning a Boolean value
  • SetPrototypeOf (target, key) : Intercepts Object.setPrototypeOf(proxy, key), returns a Boolean value. If the target object is a function, there are two additional operations that can be intercepted
  • 12, Apply (target, object, args) : intercepts Proxy instances as function calls, such as Proxy (… The args), proxy. Call (object,… The args), proxy. Apply (…).
  • Construct (Target, args) construct(target, args) : Intercepts operations called by Proxy instances as constructors, such as new Proxy (… args)

There are a total of 13 blocking methods. Here are some brief examples. For more information, see Ruan Yifeng’s Introduction to ECMAScript 6 (es6.ruanyifeng.com/#docs/proxy…

1. Get and set methods

The get method intercepts a read of a property and can take three parameters, the target object, the property name, and the proxy instance itself (strictly speaking, the object against which the action is directed), the last of which is optional.

The set intercepts the setting of the target attribute, which can take four parameters: the target object, the attribute name, the value, and the proxy instance itself (strictly speaking, the object against which the action is directed), the last of which is optional.

let target = {foo: 1} let proxy = new Proxy(target, { get(target, key, receiver) { console.log(`getter ${key}! `) return target[key] }, set: function(target, key, value, receiver) { console.log(`setter ${key}! `) target[key] = value; } }) let obj = Object.create(proxy) console.log(obj.foo) // getter foo! / / 1Copy the code

2. Has method

Intercepts the propKey in proxy operation, returning a Boolean value.

Var handler = {has (target, key) {if (key.startswith ('_')) {return false; } return key in target; }}; var foo = { _name: 'saucxs', name: 'saucxs' }; var proxy = new Proxy(foo, handler); console.log('_name' in proxy); // false console.log('name' in proxy); // trueCopy the code

3. OwnKeys method

Intercepts reads of its own properties. And returns an array of all the target object’s own property names. The specific return result can be combined with the enumerability and ownership of the MDN attribute

  • Object.getOwnPropertyName(proxy)
  • Object.getOwnPropertySymbols(proxy)
  • Object.keys(proxy)
  • for … In circulation
let target = { _foo: 'foo', _bar: 'bar', name: 'saucxs' }; let handler = { ownKeys (target) { return Reflect.ownKeys(target).filter(key => key.startsWith('_')); }}; let proxy = new Proxy(target, handler); for (let key of Object.keys(proxy)) { console.log(target[key]); } // "saucxs"Copy the code

4, the apply method

Apply intercepts the operations of Proxy instances as function calls, such as function calls (Proxy (… Args), call(proxy. Call (object,… Args), apply(proxy.apply(…) ), etc.

var target = function () { return 'I am the target'; }; var handler = { apply: function () { return 'I am the saucxs proxy'; }}; var proxy = new Proxy(target, handler); proxy(); // "I am the saucxs proxy"Copy the code

Introduction to ECMAScript 6 by Ruan Yifeng (es6.ruanyifeng.com/#docs/proxy…

All kinds of benefits

1, byte push benefits

  • Reply “school admission” to get internal push code
  • Reply “Social recruitment” to get internal promotion
  • Reply “intern” to get internal push

There will be more benefits later

2. Learning materials welfare

Reply “Algorithm” to obtain algorithm learning materials

3. One question of the day

  • Interviewer: What is the difference between “for in” and “for of”?

  • 6. How can Async/Await Async/Await Async?

  • Question 5: How does VUE data binding work?

  • Question 4: How to find repetitive elements in a scientific and efficient way?

  • 3. “Question of the Day” The interviewer asks you what you think of Promise?

  • In ES6, why do we use Symbol?

  • 1. “How does an interview question trigger deep soul searching?”

Thank you for your support

1, if you like, you can “share, like, watch” three lian oh.

2. SongEagle is a front-end engineer of Bytedance data platform, an author who is studying hard and growing up.

3, long press the picture below, pay attention to “Songbao write code”, it is to obtain the development knowledge system construction, selected articles, project actual combat, laboratory, a daily interview question, advanced learning, thinking about career development, involving JavaScript, Node, Vue, React, browser, HTTP and other fields, help more students into the “bytes, Ali, Baidu, Tencent, Didi and other big companies, I hope you are next!