In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-03-26 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
This article introduces the relevant knowledge of "how to master the reflection and agent in the front-end JavaScript". Many people will encounter such a dilemma in the operation of actual cases, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!
1. What is reflection
The concept of reflection exists in many programming languages, such as Java,C#.
In object-oriented programming, it is common to define classes and methods, and then create objects to explicitly call methods, such as the following example:
Public class User {private String name; private Date birthday; / /.... Public int calculateAgeByBirthday () {/ /. }} / / call User u = new User ("jack", new Date ()); u.calculateAgeByBirthday ()
We are familiar with the above invocation, but when you want to write some abstract frameworks (which also need to interoperate with business-defined classes), because you don't know the members and methods of the business class, the reflection dynamically gets member variables or invokes methods.
In the following example, we use reflection to convert json into a Java object.
Public static class User {private String name; public String getName () {return name;} public void setName (String name) {this.name = name;}} / / invokes the object setter method using reflection. Public static T fill (Class userClass, Map json) throws Exception {Field [] fields = userClass.getDeclaredFields (); T user = userClass.newInstance (); for (Field field: fields) {/ / initials String name = field.getName (); char [] arr = name.toCharArray (); arr [0] = Character.toUpperCase (arr [0]) System.out.println (new String (arr)); Method method = userClass.getDeclaredMethod ("set" + new String (arr), field.getType ()); Object returnValue = method.invoke (user, json.get (name));} return user;} 2, Reflect in JavaScript
JavaScript provides reflection built-in object Reflect in ES6, but reflection in JavaScript is different from Java reflection. Let's take a look at the 13 static methods provided by Reflect.
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)
2.1 Reflect.get (target, name, receiver)
The Reflect.get method finds and returns the name property of the target object, or undefined if it does not exist.
Const obj = {name: 'jack', age: 12, get userInfo () {return this.name +' age is'+ this.age;}} Reflect.get (obj, 'name') / / jackReflect.get (obj,' age') / / 12Reflect.get (obj, 'userInfo') / / jack age is 12 receiver / if the receiver parameter is passed, this points to the receiver object when the userInfo () function is called. Const receiverObj = {name: 'Xiaoming', age: 22}; Reflect.get (obj, 'userInfo', receiverObj) / / Xiaoming age is 222.2 Reflect.set (target, name, value, receiver)
Const obj = {
Name: 'jack', age: 12, set updateAge (value) {return this.age = value;},} Reflect.set (obj,' age', 22); obj.age / / 22 receiver / if the receiver parameter is passed, this points to the receiver object when the updateAge () function is called. Const receiverObj = {age: 0}; Reflect.set (obj, 'updateAge', 10, receiverObj) / / obj.age / / 22receiverObj.age / / 102.3 Reflect.has (obj, name)
The Reflect.has method is equivalent to the in operator in name in obj.
Const obj = {name: 'jack',} obj in name / / trueReflect.has (obj,' name') / / true2.4 Reflect.deleteProperty (obj, name)
The Reflect.deleteProperty method is equivalent to delete obj [name] and is used to delete properties of an object. If the deletion is successful, or the deleted attribute does not exist, return true; failed to delete, the deleted attribute still exists, and return false.
Const obj = {name: 'jack',} delete obj.name Reflect.deleteProperty (obj,' name') 2.5 Reflect.construct (target, args)
The Reflect.construct method is equivalent to new target (. Args).
The function User (name) {this.name = name;} const user = new User ('jack'); Reflect.construct (User, [' jack']); Reflect.getPrototypeOf (obj) Reflect.getPrototypeOf method is used to read the _ _ proto__ property of the object. 2.6 Reflect.setPrototypeOf (obj, newProto)
The Reflect.setPrototypeOf method is used to set the prototype of the target object. Returns a Boolean value indicating whether the setting was successful.
Const obj = {name: 'jack',} Reflect.setPrototypeOf (obj, Array.prototype); obj.length / / 02.7 Reflect.apply (func, thisArg, args)
The Reflect.apply method is equivalent to Function.prototype.apply.call (func, thisArg, args) and is used to execute the given function after binding the this object.
Const nums = [1Jing 2Jing 3Jing 4Jing 5]; const min = Math.max.apply (Math, nums); / / call const min = Reflect.apply (Math.min, Math, nums) through Reflect.apply; 2.8Reflect.defineProperty (target, propertyKey, attributes)
The Reflect.defineProperty method is the equivalent of Object.defineProperty and is used to define properties for an object.
Const obj = {}; Object.defineProperty (obj, 'property', {value: 0, writable: false}); Reflect.defineProperty (obj,' property', {value: 0, writable: false}); 2.9Reflect.getOwnPropertyDescriptor (target, propertyKey)
Gets the description object for the specified property.
2.10 Reflect.isExtensible (target)
Returns a Boolean value indicating whether the current object is extensible.
2.11 Reflect.preventExtensions (target)
Used to make an object unextensible. It returns a Boolean value indicating whether the operation was successful.
2.13 Reflect.ownKeys (target)
The Reflect.ownKeys method is used to return all the properties of the object.
Const obj = {name: 'jack', age: 12, get userInfo () {return this.name +' age is'+ this.age;}} Object.getOwnPropertyNames (obj) Reflect.ownKeys (obj) / / ['name',' age', 'userInfo'] 3, Proxy in JavaScript
Agents are useful in programming by adding a layer of "interception" in front of the target object to implement some general logic.
Proxy constructor Proxy (target, handler) parameters:
Target: the target object of the proxy, which can be any type of object, including built-in arrays, functions, proxy objects.
Handler: it is an object whose properties provide handling functions when certain operations occur.
Const user = {name: 'hello'} const proxy = new Proxy (user, {get: function (target, property) {/ / triggers return' hi';}} when reading attributes); interception supported in proxy.name / / 'hi'3.1 Proxy
Handler.get (target, property, receiver)
Handler.set (target, property, value, receiver)
Handler.has (target, property)
Handler.defineProperty (target, property, descriptor)
Handler.deleteProperty (target, property)
Handler.getOwnPropertyDescriptor (target, prop)
Handler.getPrototypeOf (target)
Handler.setPrototypeOf (target, prototype)
Handler.isExtensible (target)
Handler.ownKeys (target)
Handler.preventExtensions (target)
Handler.apply (target, thisArg, argumentsList)
Handler.construct (target, argumentsList, newTarget)
3.2 get ()
To intercept the read operation of an attribute, you can accept three parameters, namely, the target object, the property name, and the proxy instance itself, the last of which is optional.
Const user = {name: 'jack'} / / returns a value only if the attribute exists, otherwise an exception is thrown. Const proxy = new Proxy (user, {get: function (target, property) {if (! (property in target)) {throw new ReferenceError (`${property} does not room.`);} return target [property];}}); proxy.name / / jackproxy.age / / ReferenceError: age does not exist.
We can define some common proxy objects and then let the child objects inherit.
The value is returned only if the property exists, otherwise an exception is thrown. Const proxy = new Proxy ({}, {get: function (target, property) {if (! (property in target)) {throw new ReferenceError (`${property} does not room.`);} return target [property];}}); let obj = Object.create (proxy); obj.name = 'hello'obj.name / / helloobj.age / / ReferenceError: age does not exist.3.3 set ()
To intercept the assignment of an attribute, you can accept four parameters, namely, the target object, the attribute name, the attribute value, and the Proxy instance itself, the last of which is optional.
Let sizeValidator = {set: function (target, property, value, receiver) {if (typeof value = = 'string' & & value.length > 5) {throw new RangeError (' Cannot exceed 5 character.');} target [property] = value; return true;}}; const validator = new Proxy ({}, sizeValidator); let obj = Object.create (validator) Obj.name = '123456' / / RangeError: Cannot exceed 5 character.obj.age = 12 / / 123.4 has ()
This method takes effect when it is used to intercept HasProperty operations, that is, to determine whether an object has a property. Such as the in operator.
It accepts two parameters, namely, the target object and the name of the attribute to be queried.
Const handler = {has (target, key) {if (key [0] = ='_') {return false;} return key in target;}}; var target = {_ prop: 'foo', prop:' foo'}; var proxy = new Proxy (target, handler);'_ prop' in proxy / / false3.5 defineProperty ()
The defineProperty () method intercepts the Object.defineProperty () operation.
3.6 deleteProperty ()
Used to intercept delete operations, and if this method throws an error or returns false, the current property cannot be deleted by the delete command.
3.7 getOwnPropertyDescriptor ()
The getOwnPropertyDescriptor () method intercepts Object.getOwnPropertyDescriptor () and returns a property description object or undefined.
3.8 getPrototypeOf ()
It is mainly used to intercept and acquire object prototypes. The operations to intercept are as follows:
Object.getPrototypeOf ()
Reflect.getPrototypeOf ()
_ _ proto__
Object.prototype.isPrototypeOf ()
Instanceof
Const obj = {}; const proto = {}; const handler = {getPrototypeOf (target) {console.log (target = obj); / / true console.log (this = handler); / / true return proto;}}; const p = new Proxy (obj, handler); console.log (Object.getPrototypeOf (p) = proto); / / true3.9 setPrototypeOf ()
It is mainly used to intercept the Object.setPrototypeOf () method.
Const handlerReturnsFalse = {setPrototypeOf (target, newProto) {return false;}}; const newProto = {}, target = {}; const p1 = new Proxy (target, handlerReturnsFalse); Object.setPrototypeOf (p1, newProto); / / throws a TypeErrorReflect.setPrototypeOf (p1, newProto); / / returns false3.10 isExtensible ()
Method to intercept Object.isExtensible () operations.
Const p = new Proxy ({}, {isExtensible: function (target) {console.log ('called'); return true;// can also be return 1; the value expressed as true}}); console.log (Object.isExtensible (p)); / / "called" / / true3.11 ownKeys ()
Used to intercept the read operation of the object's own properties. Specifically, intercept the following operations.
Object.getOwnPropertyNames ()
Object.getOwnPropertySymbols ()
Object.keys ()
For...in loop.
Const p = new Proxy ({}, {ownKeys: function (target) {console.log ('called'); return [' await, 'baked,' c'];}}); console.log (Object.getOwnPropertyNames (p)); / / "called" 3.12 preventExtensions ()
Used to intercept Object.preventExtensions (). The method must return a Boolean value, otherwise it will be automatically converted to a Boolean value.
This method has a limitation that proxy.preventExtensions can return true only if the target object is not extensible (that is, Object.isExtensible (proxy) is false), otherwise an error will be reported.
Const p = new Proxy ({}, {preventExtensions: function (target) {console.log ('called'); Object.preventExtensions (target); return true;}}); console.log (Object.preventExtensions (p)); / / "called" / / false3.13 apply ()
The apply method intercepts the following actions.
Proxy (. Args)
Function.prototype.apply () and Function.prototype.call ()
Reflect.apply ()
It accepts three parameters, namely, the target object, the context object of the target object (this), and the parameter array of the target object.
Const handler = {apply (target, ctx, args) {return Reflect.apply (..);}}
Example:
Const target = function () {}; const handler = {apply: function (target, thisArg, argumentsList) {console.log ('called:' + argumentsList.join (','); return argumentsList [0] + argumentsList [1] + argumentsList [2];}}; const p = new Proxy (target, handler); p (1meme 2jue 3) / / "called: 1Jing 2jue 3" 63.14 construct ()
Used to intercept new commands. The following is how to write the intercepted object:
Const handler = {construct (target, args, newTarget) {return new target (.. ARGs);}}
Its method accepts three parameters.
Target: target object.
Args: an array of arguments to the constructor.
NewTarget: the constructor that the new command acts on when creating an instance object.
Note: the method must return an object, and the target object must be a function, otherwise an error will be reported.
Const p = new Proxy (function () {}, {construct: function (target, argumentsList) {return 0;}}); new p () / / return value is not an object, const p = new Proxy ({}, {construct: function (target, argumentsList) {return {};}}); new p () / / target object is not a function, error 4, observer mode
Observer is a commonly used pattern, which is defined as when the state of an object changes, all objects that depend on it are notified and updated automatically.
We use Proxy to implement an example that lets the observation function execute automatically when the state of the object changes.
Observer function, wrap the observation target, and add the observation function.
Observable wraps the observation target and returns a Proxy object.
Observe adds an observer function to the queue.
Const queuedObservers = new Set (); const observe = fn = > queuedObservers.add (fn); const observable = obj = > new Proxy (obj, {set}); / / when the attribute changes, the observation function is executed automatically. Function set (target, key, value, receiver) {const result = Reflect.set (target, key, value, receiver); queuedObservers.forEach (observer = > observer ()); return result;}
Example:
Const user = observable ({name: 'jack', age: 20}); function userInfo () {console.log (`${user.name}, ${user.age}`)} observe (userInfo); user.name =' Xiaoming'; / / Xiaoming, 20 "how to master reflection and proxy in front-end JavaScript" ends here, thank you for reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.