162, Proxy and Reflect


Source http://caibaojian.com/es6/proxy.html Proxy interceptor same object may be provided to intercept a plurality of operations.
1、Proxy var obj = new Proxy({}, { get: function (target, key, receiver) { /* target: the target object property: property name receiver: Behavior object operation is directed, generally refers proxy instance itself */ if (key === 'prototype') { return Object.prototype; } return 'Hello, ' + key; }, set: function (target, key, value, receiver) { /* target: the target object propertyName: attribute name propertyValue: Property Value receiver: Proxy instance itself */ console.log(`setting ${key}!`); return Reflect.set(target, key, value, receiver); }, apply: function (target, key, receiver) { return receiver[0]; }, construct: function (target, key) { return { value: key[1] }; } }); obj.count; obj.count = 1 The following is a list of Proxy support of interception. May be provided for, but is not provided to intercept operation, it is directly on the target object, generating results as originally manner. 1)get(target, propKey, receiver) Intercepting object read attribute, such proxy.foo and Proxy [ 'foo' ]. The last parameter is an object receiver, optional, see the section below Reflect.get. 2)set(target, propKey, value, receiver) Disposed to intercept the object properties, such proxy.foo = v or Proxy [ 'foo' ] = V, returns a Boolean value. 3)has(target, propKey) PropKey in proxy intercepting operation, and a method hasOwnProperty object returns a Boolean value. 4)deleteProperty(target, propKey) Interception delete proxy [propKey] operation returns a Boolean value. 5)ownKeys(target) Interception Object.getOwnPropertyNames (proxy), Object.getOwnPropertySymbols (proxy), Object.keys (proxy), returns an array. This method returns the object itself all the attributes, Object.keys () returns only traverse the object attributes. 6)getOwnPropertyDescriptor(target, propKey) Interception Object.getOwnPropertyDescriptor (proxy, propKey), returns the object property described. 7)defineProperty(target, propKey, propDesc) Interception Object.defineProperty (proxy, propKey, propDesc), Object.defineProperties (proxy, propDescs), returns a Boolean value. 8)preventExtensions(target) Interception Object.preventExtensions (proxy), returns a Boolean value. 9)getPrototypeOf(target) Interception Object.getPrototypeOf (proxy), returns an object. 10)isExtensible(target) Interception Object.isExtensible (proxy), returns a Boolean value. 11)setPrototypeOf(target, proto) Interception Object.setPrototypeOf (proxy, proto), returns a Boolean value. If the target object is a function, then there are two additional operations can be intercepted. 12)apply(target, object, args) Proxy instance as an operation to intercept a function call, such as proxy (... args), proxy.call (object, ... args), proxy.apply (...). 13)construct(target, args) 2 , Reflect Overview Reflect an object with Proxy objects, but also objects ES6 provided to operate the new API. Reflect an object designed to have several. ( 1 ) clearly belong to some of the internal language methods (such Object.defineProperty) Object object, the object placed on Reflect. At this stage, while some methods on objects Reflect Object and deployment of new methods in the future will only be deployed on Reflect objects. ( 2 ) Modify Object returns some result of the method, let it becomes more reasonable. For example, Object.defineProperty (obj, name, desc ) when the property can not be defined, it will throw an error, but Reflect.defineProperty (obj, name, desc) will return false. // old wording try { Object.defineProperty(target, property, attributes); // success } catch (e) { // failure } // 新写法 if (Reflect.defineProperty(target, property, attributes)) { // success } else { // failure } ( 3 ) Let Object operations becomes a function of behavior. Some Object operations are imperative, such as name in obj and delete obj [name], and Reflect.has (obj, name) and Reflect.deleteProperty (obj, name) so that they become a function of behavior. // old wording 'assign' in Object // true // The new wording Reflect.has(Object, 'assign') // true (4 Method) Reflect objects and objects correspond Proxy method, as long as the Proxy object methods, a method can be found in the corresponding Reflect object. This allows Proxy object can call the corresponding Reflect method to easily complete the default behavior, as a basis for modifying behavior. In other words, no matter how Proxy modify the default behavior, you can always get the default behavior on Reflect. Proxy(target, { set: function (target, name, value, receiver) { var success = Reflect.set(target, name, value, receiver); if (success) { log('property ' + name + ' on ' + target + ' set to ' + value); } return success; } }); The above code, Proxy property assignment method to intercept the behavior of target objects. It uses Reflect.set attribute value assigned to the method of the object, and then the deployment of additional features. Here is another example. var loggedObj = new Proxy(obj, { get(target, name) { console.log('get', target, name); return Reflect.get(target, name); }, deleteProperty(target, name) { console.log('delete' + name); return Reflect.deleteProperty(target, name); }, has(target, name) { console.log('has' + name); return Reflect.has(target, name); } }); The above code, each Proxy object interception (get, delete, has), invokes the corresponding internal Reflect method, can be performed to ensure that the behavior of native normal. Add job is to operate each output line of the log. With Reflect objects after many operations will be easier to read. // old wording Function.prototype.apply.call(Math.floor, undefined, [1.75]) // 1 // The new wording Reflect.apply(Math.floor, undefined, [1.75]) // 1 Methods Reflect objects The method follows the object list Reflect, a total of 13. Reflect.apply(target, thisArg, args) Reflect.construct(target, args) Reflect.get(target, name, receiver) Reflect.set(target, name, value, receiver) Reflect.defineProperty(target, name, desc) Reflect.deleteProperty(target, name) Reflect.has(target, name) Reflect.ownKeys(target) Reflect.isExtensible(target) Reflect.preventExtensions(target) Reflect.getOwnPropertyDescriptor(target, name) Reflect.getPrototypeOf(target) Reflect.setPrototypeOf(target, prototype) Effect of these methods above, the method of action of the majority of the Object object with the same name are the same, and methods of the Proxy object it is one to one. The following is an explanation of several of these methods. 1)Reflect.get(target, name, receiver) Find and return the target name attributes of the object, if not the property, undefined is returned. If the name attribute to deploy the Read function, the function of this binding is read receiver. var obj = { get foo() { return this.bar(); }, bar: function () { ... } }; // the following statement will this.bar () // becomes a call wrapper.bar () Reflect.get(obj, "foo", wrapper);2)Reflect.set(target, name, value, receiver) Setting target object name attribute equal value. If the name attribute set assigned function, the function of this assignment binding receiver. 3)Reflect.has(obj, name) Equivalent to the name in obj. 4)Reflect.deleteProperty(obj, name) Equivalent to delete obj [name]. 5)Reflect.construct(target, args) Is equivalent to the new target (... args), a method is provided which does not use new, to call the constructor. 6)Reflect.getPrototypeOf(obj) __Proto__ property of the object to be read, corresponding to Object.getPrototypeOf (obj). 7)Reflect.setPrototypeOf(obj, newProto) __Proto__ property object set, corresponding to Object.setPrototypeOf (obj, newProto). 8)Reflect.apply(fun, thisArg, args) Equivalent to Function.prototype.apply.call (fun, thisArg, args). In general, if you want to bind this object is a function, you can write fn.apply (obj, args), but if the function definition apply its own method, it can only be written Function.prototype.apply.call (fn, obj, args), Reflect objects using this operation can be simplified. Also, note that, Reflect.set (), Reflect.defineProperty (), Reflect.freeze (), Reflect.seal () and Reflect.preventExtensions () returns a Boolean value indicating whether the operation was successful. Object methods for their corresponding failure will throw an error. Throws // failure error Object.defineProperty (obj, name, desc) ; return false // when failure Reflect.defineProperty (obj, name, desc) ; In the above code, function and Object.defineProperty Reflect.defineProperty method is the same, is an attribute defined for the object. However, Reflect.defineProperty method fails, will not throw an error, it will only return false. Example: Proxy implemented using the observer pattern The observer pattern (Observer mode) refers to a function of automatic observation data object, once the object has changed, the function will be executed automatically. const person = observable({ name: "Joe Smith" , age: 20 }); function print() { console.log(`${person.name}, ${person.age}`) } observe(print); PERSON.NAME = 'John Doe' ; // output // John Doe, 20 in the above code, the data object is an observation target person, print function observer. Once the data object changes, print will be executed automatically. Next, write a Proxy observer mode easiest to achieve, namely to achieve observable and observe these two functions. The idea is observable function returns an original object Proxy proxy, intercepting assignment, triggering various functions act as observer. const queuedObservers = new Set(); const observe = fn => queuedObservers.add(fn); const observable = obj => new Proxy(obj, { set }); function set(target, key, value, receiver) { const result = Reflect.set(target, key, value, receiver); queuedObservers.forEach(observer => observer()); return result; } The above code, first define a Set collection, all observers functions into this collection. Then, observable function returns the original object proxy, intercepting assignment. Among the interception function set, automatically performs all observers.

 

Guess you like

Origin www.cnblogs.com/gushixianqiancheng/p/11929936.html