当前位置:网站首页>ES6 - study notes
ES6 - study notes
2022-07-25 03:03:00 【Aviator_ huahua】
1、let、var、const
var:
Function scope , There is variable promotion , Repeatable statement
let:
Block level scope , No variable promotion , Not to repeat , There is a temporary dead zone problem ( Within the block level scope , Use global variables and then let Declare a variable with the same name , It will lead to an error )
const:
Used to declare constants , Must be declared with a value , Once defined, it cannot be modified , Non repeatable assignment .
Block level scope , No variable promotion , Not to repeat , There is a temporary dead zone problem
2、 Deconstruct assignment
ES6 Allow to follow certain mode , Extract values from arrays and objects , Assign values to variables , This is called deconstruction (Destructuring).
Array deconstruction assignment
You can extract values from arrays , According to the corresponding position , Assign a value to a variable .
Essentially , This is the way it's written “ Pattern matching ”, As long as the patterns on both sides of the equal sign are the same , The variable on the left is given the corresponding value .
let [a, b, c] = [1, 2, 3]; // a = 1 ,b = 2, c = 3
let [foo, [[bar], baz]] = [1, [[2], 3]]; // foo = 1 ,bar = 2, baz = 3
let [ , , third] = ["foo", "bar", "baz"]; // third = "baz"
let [x, , y] = [1, 2, 3]; // x = 1, y = 3
let [head, ...tail] = [1, 2, 3, 4]; // head = 1, tail = [2, 3, 4]
let [x, y, ...z] = ['a']; // x = "a", y = undefined, z = []
// Incomplete deconstruction
let [x, y] = [1, 2, 3]; // x = 1, y = 2
let [a, [b], d] = [1, [2, 3], 4]; // a = 1, b = 2, d = 4
// Assign default
let [x, y = 'b'] = ['a']; // x = 'a', y = 'b'
let [x, y = 'b'] = ['a', undefined]; // x = 'a', y = 'b'
let [x, y = 'b'] = ['a', 'c']; // x = 'a', y = 'c'
If deconstruction is not successful , The value of the variable is equal to undefined.
let [foo] = []; // foo = undefined
let [bar, foo] = [1]; // bar = 1, foo = undefined
If the right side of the equals sign is not an array ( Or, strictly speaking , Not ergodic structures ), Then there will be an error .
// Report errors
let [foo] = 1;
let [foo] = false;
let [foo] = NaN;
let [foo] = undefined;
let [foo] = null;
let [foo] = {
};
Object deconstruction assignment
An important difference between object deconstruction and array . The elements of an array are ordered , The value of a variable depends on its position ; The properties of an object have no order , Variable must have the same name as property , To get the right value .
let {
bar, foo } = {
foo: 'aaa', bar: 'bbb' }; // foo = "aaa", bar = "bbb"
let {
baz } = {
foo: 'aaa', bar: 'bbb' }; // baz = undefined
If deconstruction fails , The value of the variable is equal to undefined.
let {
foo} = {
bar: 'baz'}; // foo = undefined
If the variable name is not the same as the property name , It must be written as follows .
let obj = {
first: 'hello', last: 'world' };
let {
first: f, last: l } = obj; // f = 'hello', l = 'world'
This actually means , The deconstruction assignment of an object is short for the following form
let {
foo: foo, bar: bar } = {
foo: 'aaa', bar: 'bbb' };
in other words , The internal mechanism of object's Deconstruction and assignment , First find the attribute with the same name , And then assign it to the corresponding variable . What is really assigned is the latter , Not the former .
let {
foo: baz } = {
foo: 'aaa', bar: 'bbb' };
baz // "aaa"
foo // error: foo is not defined
Be careful , The object's deconstruction assignment can take the inherited property .
const obj1 = {
};
const obj2 = {
foo: 'bar' };
Object.setPrototypeOf(obj1, obj2);
const {
foo } = obj1;
foo // "bar"
3、 Template string
Template string (template string) It's an enhanced string , Use back quotes (`) identification . It can be used as a normal string , It can also be used to define multiline strings , Or embed variables in strings . Embed variables in the template string , You need to write the variable name in ${} In .
// Normal string
`In JavaScript '\n' is a line-feed.`
// Multiline string
`In JavaScript this is not legal.`
console.log(`string text line 1 string text line 2`);
// Embed variables in string
let name = "Bob", time = "today";
`Hello ${
name}, how are you ${
time}?`
4、 String adding method
includes(), startsWith(), endsWith()
Traditionally ,JavaScript Only indexOf Method , Can be used to determine if a string is contained in another string .ES6 Three new methods are provided .
- includes(): Returns a Boolean value , Indicates whether the parameter string was found .
- startsWith(): Returns a Boolean value , Indicates whether the parameter string is in the header of the original string .
- endsWith(): Returns a Boolean value , Indicates whether the parameter string is at the end of the original string .
let s = 'Hello world!';
s.startsWith('Hello') // true
s.endsWith('!') // true
s.includes('o') // true
All three methods support the second parameter , Indicates where to start the search . Use the second parameter n when ,endsWith Our behavior is different from the other two methods . It's for the front n Characters , And the other two methods are from n Positions until the end of the string .
let s = 'Hello world!';
s.startsWith('world', 6) // true
s.endsWith('Hello', 5) // true
s.includes('Hello', 6) // false
repeat()
repeat Method returns a new string , Means to repeat the original string n Time .
'x'.repeat(3) // "xxx"
'hello'.repeat(2) // "hellohello"
'na'.repeat(0) // ""
replace(),replaceAll()
String instance method replace() Only the first match can be replaced . If you want to replace all matches , You have to use regular expressions g Modifier .
'aabbcc'.replace('b', '_')
// 'aa_bcc'
'aabbcc'.replace(/b/g, '_')
// 'aa__cc'
replaceAll() Method , You can replace all matches at once .
'aabbcc'.replaceAll('b', '_')
// 'aa__cc'
5、 Arrow function
var f = v => v;
// Equate to
var f = function (v) {
return v;
};
The arrow function has several points for attention .
(1) Arrow function does not have its own this object .
(2) Can't be used as a constructor , in other words , You cannot use... For arrow functions new command , Otherwise, an error will be thrown .
(3) Not available arguments object , The object does not exist inside the function . If you want to use , It can be used rest Parameters instead of .
(4) Not available yield command , So the arrow function cannot be used as Generator function .
In the four points above , The most important thing is the first point . For ordinary functions , Inside this Point to the object where the function runs , But this is not true for arrow functions . It doesn't have its own this object , Inside this It's defined in the upper scope this. in other words , Inside the arrow function this The point is fixed , by comparison , Of a normal function this The direction is variable .
6、 Operator expansion
Exponential operators **
One of the characteristics of this operator is right combination , It's not the common left combination . When multiple exponential operators are used together , From the far right .
// amount to 2 ** (3 ** 2)
2 ** 3 ** 2
// 512
The exponent operator can be combined with an equal sign , Form a new assignment operator (**=).
let b = 4;
b **= 3;
// Equate to b = b * b * b;
Chain judgment operator ?.
Use ?. Operator , It will be judged directly when the chain call , Whether the object on the left is null or undefined. If yes, , It's not going to go down , It's going back to undefined.
Used to judge whether the attribute of an object exists , Ensure that no error is reported when taking values .
let person={
id:1,
info:{
name:'xiaoming',
age:20,
address:'shanghai'
}
}
let name=person?.info?.name||'zs' // xiaoming
let address=person?.info123?.address||'beijing' //beijing
let address1=person.info123.address||'beijing' // Report errors
Determine whether the object method exists , Examples of immediate execution if any .
person.say?.() // Nothing happened
Chain judgment operator ?. There are three ways of writing .
obj?.prop// Does the object property existobj?.[expr]// dittofunc?.(...args)// Whether a function or object method exists
Here is ?. Common forms of operators , And the equivalent form when the operator is not used .
a?.b
amount to a==null?undefined:a.b
a?.[x]
amount to a==null?undefined:a[x]
a?.b()
amount to a==null?undefined:a.b() // Be careful , If a.b Exists but is not a function , Will be an error
a?.()
amount to a==null?undefined:a() // Be careful , If a Exists but is not a function , Will be an error
Be careful :
Short circuit mechanism
Essentially ,
?.Operator is equivalent to a short circuit mechanism , As long as the conditions are not met , No more execution .a?.[++x] // Equate to a == null ? undefined : a[++x]In the above code , If
ayesundefinedornull, thatxNo increment operation . in other words , Once the chain judgment operator is true , The expression on the right is no longer evaluated .The effect of parentheses
If the attribute chain has parentheses , The chain judgment operator has no effect on the outside of the parentheses , It only affects the inside of parentheses .
(a?.b).c // Equivalent to (a == null ? undefined : a.b).cIn the above code ,
?.It has no effect on the outside of the parentheses , No matteraWhether the object exists , After parentheses.cAlways execute .Generally speaking , Use
?.Operator , Parentheses should not be used .Error reporting occasion
The following wording is prohibited , Will report a mistake .
// Constructors new a?.() new a?.b() // There is a template string on the right side of the chain judgment operator a?.`{b}` a?.b`{c}` // The left side of the chain judgment operator is super super?.() super?.foo // The chain operator is used to the left of the assignment operator a?.b = cThe right side must not be decimal
To ensure compatibility with previous code , allow
foo?.3:0Is parsed intofoo ? .3 : 0, Therefore, it is stipulated that if?.Followed by a decimal number , that?.It is no longer regarded as a complete operator , It will be handled according to the ternary operator , in other words , That decimal point will belong to the following decimal number , Form a decimal .
Null Judgment operator ??
When reading object properties , If the value of a property is null or undefined, Sometimes you need to specify default values for them . A common practice is through || Operator to specify the default value .
const headerText = response.settings.headerText || 'Hello, world!';
const animationDuration = response.settings.animationDuration || 300;
const showSplashScreen = response.settings.showSplashScreen || true;
The above three lines of code pass || Operator to specify the default value , But this is wrong . The developer's original intention is , As long as the value of the attribute is null or undefined, The default value will take effect , However, if the value of the property is an empty string or false or 0, The default value will also take effect .
To avoid that ,ES2020 Introduced a new Null Judgment operator ??. It behaves like ||, But only the value to the left of the operator is null or undefined when , To return the value on the right .
const headerText = response.settings.headerText ?? 'Hello, world!';
const animationDuration = response.settings.animationDuration ?? 300;
const showSplashScreen = response.settings.showSplashScreen ?? true;
In the above code , The default value is only on the left. The attribute value is null or undefined when , Will take effect .
One purpose of this operator , It's the chain judgment operator ?. In combination with , by null or undefined Set the default value .
const animationDuration = response.settings?.animationDuration ?? 300;
In the above code , If response.settings yes null or undefined, perhaps response.settings.animationDuration yes null or undefined, It will return the default value 300. in other words , This line of code includes two levels of attribute judgment .
?? It's essentially a logical operation , It works with two other logical operators && and || There is a priority issue , Which is the priority between them . Different priorities , It often leads to different results of logical operations .
Now the rule is , If multiple logical operators are used together , Priority must be indicated in parentheses , Otherwise, an error will be reported .
// Report errors
lhs && middle ?? rhs
lhs ?? middle && rhs
lhs || middle ?? rhs
lhs ?? middle || rhs
// normal
(lhs && middle) ?? rhs;
lhs && (middle ?? rhs);
(lhs ?? middle) && rhs;
lhs ?? (middle && rhs);
(lhs || middle) ?? rhs;
lhs || (middle ?? rhs);
(lhs ?? middle) || rhs;
lhs ?? (middle || rhs);
Logical assignment operators ||=,&&=,??=
ES2021 Three new Logical assignment operators (logical assignment operators), Combine logical operators with assignment operators .
// Or assignment operator
x ||= y
// Equate to
x || (x = y)
// And assignment operator
x &&= y
// Equate to
x && (x = y)
// Null Assignment operator
x ??= y
// Equate to
x ?? (x = y)
These three operators ||=、&&=、??= It is equivalent to performing logical operation first , Then according to the calculation results , Then carry out assignment operation according to the situation .
One of their uses is , Set default values for variables or properties .
// The old way of writing
user.id = user.id || 1;
// A new way of writing
user.id ||= 1;
// The old way of writing
function example(opts) {
opts.foo = opts.foo ?? 'bar';
opts.baz ?? (opts.baz = 'qux');
}
// A new way of writing
function example(opts) {
opts.foo ??= 'bar';
opts.baz ??= 'qux';
}
7、Symbol
summary
ES5 Object property names are strings , This can easily cause property name conflicts . such as , You used an object that someone else provided , But I want to add a new method to this object (mixin Pattern ), The name of the new method may conflict with the existing method . If there is a mechanism , Just make sure that the name of each attribute is unique , This will fundamentally prevent the conflict of attribute names . This is it. ES6 introduce Symbol Why .
ES6 A new type of raw data is introduced Symbol, Represents a unique value . It belongs to JavaScript One of the data types of language , Other data types are :undefined、null、 Boolean value (Boolean)、 character string (String)、 The number (Number)、 Large integer (BigInt)、 object (Object).
Symbol Value through Symbol() Function generation . That is to say , Object property names can now be of two types , One is the original string , The other is the new Symbol type . All attribute names belong to Symbol type , It's all unique , You can ensure that there is no conflict with other property names .
let s = Symbol();
typeof s
// "symbol"
In the above code , Variable s It's a unique value .typeof The result of the operator , Indicates the variable s yes Symbol data type , Instead of other types like strings .
Be careful ,Symbol Cannot use before function new command , Otherwise, an error will be reported . This is because of the creation of Symbol Is a primitive type of value , Not object . in other words , because Symbol Value is not an object , So you can't add properties . Basically , It is a data type similar to a string .
Symbol Function can take a string as an argument , Said to Symbol Description of the example , Mainly for display on the console , Or to string , Easy to distinguish .
let s1 = Symbol('foo');
let s2 = Symbol('bar');
s1 // Symbol(foo)
s2 // Symbol(bar)
s1.toString() // "Symbol(foo)"
s2.toString() // "Symbol(bar)"
In the above code ,s1 and s2 Are the two Symbol value . If you don't add parameters , Their output on the console is Symbol(), It's not good to distinguish . With parameters , It's like adding a description to them , When you output, you can distinguish , Which value is it .
If Symbol The argument to is an object , Will call the object toString Method , Turn it into a string , And then generate a Symbol value .
const obj = {
toString() {
return 'abc';
}
};
const sym = Symbol(obj);
sym // Symbol(abc)
Be careful ,Symbol The arguments to the function are just for the current Symbol Description of value , So... With the same parameters Symbol The return value of the function is not equal .
// Without parameters
let s1 = Symbol();
let s2 = Symbol();
s1 === s2 // false
// With parameters
let s1 = Symbol('foo');
let s2 = Symbol('foo');
s1 === s2 // false
Symbol Value cannot be evaluated with other types of values , Will report a mistake .
let sym = Symbol('My symbol');
"your symbol is " + sym
// TypeError: can't convert symbol to string
`your symbol is ${
sym}`
// TypeError: can't convert symbol to string
however ,Symbol Values can be explicitly converted to strings .
let sym = Symbol('My symbol');
String(sym) // 'Symbol(My symbol)'
sym.toString() // 'Symbol(My symbol)'
in addition ,Symbol Values can also be converted to Boolean values , But it can't be converted to a numerical value .
let sym = Symbol();
Boolean(sym) // true
!sym // false
if (sym) {
// ...
}
Number(sym) // TypeError
sym + 2 // TypeError
Symbol.prototype.description
establish Symbol When , You can add a description . however , Reading this description requires Symbol Explicit conversion to string , That is, the following writing .
const sym = Symbol('foo');
String(sym) // "Symbol(foo)"
sym.toString() // "Symbol(foo)"
The above usage is not very convenient .ES2019 An instance property is provided description, Go straight back to Symbol Description of .
const sym = Symbol('foo');
sym.description // "foo"
As the property name Symbol value
Because of each Symbol The values are all unequal , It means Symbol A value can be used as an identifier , The property name used for the object , It's guaranteed that there won't be properties with the same name . This is very useful when an object is made up of multiple modules , Can prevent a key from being accidentally rewritten or overridden .
let mySymbol = Symbol();
// The first way to write it
let a = {
};
a[mySymbol] = 'Hello!';
// The second way
let a = {
[mySymbol]: 'Hello!'
};
// The third way
let a = {
};
Object.defineProperty(a, mySymbol, {
value: 'Hello!' });
// All of the above results are the same
a[mySymbol] // "Hello!"
Inside the object , Use Symbol When the value defines a property ,Symbol The value must be in square brackets .
let s = Symbol();
let obj = {
[s](arg) {
... }
};
There's one more thing to note ,Symbol Value as property name , This property is also a public property , It's not a private property .
8、Set、Map
Set
ES6 Provides a new data structure Set. It's like an array , But the values of the members are unique , There are no duplicate values .
Set Itself a constructor , Used to generate Set data structure .Set The function accepts an array ( Or with iterable Other data structures of the interface ) As a parameter , Used to initialize , It can also be done through add() The method can be applied to Set Structure add data members .
// Patients with a
const set = new Set([1, 2, 3, 4, 4]);
[...set]
// [1, 2, 3, 4]
// Example 2
const items = new Set([1, 2, 3, 4, 5, 5, 5, 5]);
items.size // 5
// Example 3
const set = new Set(document.querySelectorAll('div'));
set.size // 56
// Be similar to
const set = new Set();
document
.querySelectorAll('div')
.forEach(div => set.add(div));
set.size // 56
Set Structure can be used for array de duplication
// Remove duplicate members of the array
[...new Set(array)]
towards Set When adding value , No type conversion will occur , therefore 5 and "5" It's two different values .Set Internally determine whether the two values are different , The algorithm used is called “Same-value-zero equality”, It's similar to the exact equality operator (===), The main difference is to Set When we add value, we think that NaN Equal to itself , And the exact equality operator says NaN It's not equal to itself .
let set = new Set();
let a = NaN;
let b = NaN;
set.add(a);
set.add(b);
set // Set {NaN}
Set Instance properties and methods
Set Instances of structures have the following properties .
Set.prototype.constructor: Constructors , The default isSetfunction .Set.prototype.size: returnSetThe total number of members of the instance .
Set The methods of examples fall into two categories : Operation method ( For operation data ) And traversal methods ( Used to traverse members ). Here are four operation methods .
Set.prototype.add(value): Add a value , return Set Structure itself .Set.prototype.delete(value): Delete a value , Returns a Boolean value , Indicates whether the deletion is successful .Set.prototype.has(value): Returns a Boolean value , Indicates whether the value isSetMembers of .Set.prototype.clear(): Clear all members , no return value .
Set Traversal operation
Set An instance of a structure has four traversal methods , Can be used to traverse members .
Set.prototype.keys(): Returns the traverser of the key nameSet.prototype.values(): The traverser that returns the key valueSet.prototype.entries(): Returns the traverser of the key value pairSet.prototype.forEach(): Use the callback function to traverse each member
It is important to note that ,Set The traversal order of is the insertion order . This feature is sometimes very useful , For example, use Set Save a list of callback functions , When called, it can be called in the order of addition .
(1)keys(),values(),entries()
keys Method 、values Method 、entries Methods return traverser objects ( See 《Iterator object 》 chapter ). because Set Structure has no key name , Only key value ( Or the key name and the key value are the same value ), therefore keys Methods and values Methods behave exactly the same .
let set = new Set(['red', 'green', 'blue']);
for (let item of set.keys()) {
console.log(item);
}
// red
// green
// blue
for (let item of set.values()) {
console.log(item);
}
// red
// green
// blue
for (let item of set.entries()) {
console.log(item);
}
// ["red", "red"]
// ["green", "green"]
// ["blue", "blue"]
In the above code ,entries Method returns the traverser , Include both key name and key value , So one array at a time , Its two members are exactly equal .
Set The instance of structure is traversable by default , Its default traverser generator function is its values Method .
Set.prototype[Symbol.iterator] === Set.prototype.values
// true
It means , It can be omitted values Method , Direct use for...of Loop traversal Set.
let set = new Set(['red', 'green', 'blue']);
for (let x of set) {
console.log(x);
}
// red
// green
// blue
(2)forEach()
Set An instance of a structure is the same as an array , Also have forEach Method , Used to perform some kind of operation on each member , no return value .
let set = new Set([1, 4, 9]);
set.forEach((value, key) => console.log(key + ' : ' + value))
// 1 : 1
// 4 : 4
// 9 : 9
(3) The application of traversal
Extension operator (...) For internal use for...of loop , So it can also be used for Set structure .
let set = new Set(['red', 'green', 'blue']);
let arr = [...set];
// ['red', 'green', 'blue']
Map
JavaScript The object of (Object), It's essentially a set of key value pairs (Hash structure ), But traditionally only strings are used as keys . This has brought a great limit to its use .
const data = {
};
const element = document.getElementById('myDiv');
data[element] = 'metadata';
data['[object HTMLDivElement]'] // "metadata"
The original meaning of the above code is to put a DOM Nodes as objects data Key , But because objects only accept strings as key names , therefore element Is automatically converted to a string [object HTMLDivElement].
To solve this problem ,ES6 Provides Map data structure . It's like an object , It's also a set of key value pairs , however “ key ” Is not limited to strings , Various types of values ( Including objects ) Can be used as a key . in other words ,Object Structure provides “ character string — value ” Corresponding ,Map Structure provides “ value — value ” Corresponding , Is a more perfect Hash Structure implementation . If you need “ Key value pair ” Data structure of ,Map Than Object More appropriate .
const m = new Map();
const o = {
p: 'Hello World'};
m.set(o, 'content')
m.get(o) // "content"
m.has(o) // true
m.delete(o) // true
m.has(o) // false
As constructor ,Map You can also accept an array as an argument . The members of the array are arrays representing key value pairs .
const map = new Map([
['name', ' Zhang San '],
['title', 'Author']
]);
map.size // 2
map.has('name') // true
map.get('name') // " Zhang San "
map.has('title') // true
map.get('title') // "Author"
If you assign multiple values to the same key , The later value will override the previous value .
const map = new Map();
map
.set(1, 'aaa')
.set(1, 'bbb');
map.get(1) // "bbb"
If you read an unknown key , Then return to undefined.
new Map().get('asfddfsasadf')
// undefined
Be careful , Only references to the same object ,Map The structure treats it as the same key . Be very careful about this .
const map = new Map();
map.set(['a'], 555);
map.get(['a']) // undefined
Code above set and get Method , The surface is for the same key , But in fact, these are two different array instances , Memory addresses are different , therefore get Method cannot read the key , return undefined.
If Map Is a simple type of value ( Numbers 、 character string 、 Boolean value ), Then as long as the two values are strictly equal ,Map Think of it as a key , such as 0 and -0 It's just a key , Boolean value true And string true Two different keys . in addition ,undefined and null It's also two different keys . although NaN Not strict is equal to oneself , but Map Think of it as the same key .
let map = new Map();
map.set(-0, 123);
map.get(+0) // 123
map.set(true, 1);
map.set('true', 2);
map.get(true) // 1
map.set(undefined, 3);
map.set(null, 4);
map.get(undefined) // 3
map.set(NaN, 123);
map.get(NaN) // 123
Map The properties and operation methods of the instance
Map Instances of structures have the following properties .
Map.prototype.size: returnMapThe total number of members of the instance .
Map Example method .
Map.prototype.set(key,value):setMethod to set the key namekeyThe corresponding key value isvalue, Then go back to the whole Map structure . IfkeyThere has been a value , Then the key value will be updated , Otherwise, the new key will be generated .setMethod returns the currentMapobject , So we can do the chain notation .let map = new Map() .set(1, 'a') .set(2, 'b') .set(3, 'c');Map.prototype.delete(value):deleteMethod to delete a key , returntrue. If the deletion fails , returnfalse.const m = new Map(); m.set(undefined, 'nah'); m.has(undefined) // true m.delete(undefined) m.has(undefined) // falseMap.prototype.has(value):hasMethod returns a Boolean value , Indicates whether a key is currently Map Among objects .const m = new Map(); m.set('edition', 6); m.set(262, 'standard'); m.set(undefined, 'nah'); m.has('edition') // true m.has('years') // false m.has(262) // true m.has(undefined) // trueMap.prototype.clear():clearMethod to remove all members , no return value .Map.prototype.get(key):getMethod readingkeyCorresponding key value , If you can't find itkey, returnundefined.const m = new Map(); const hello = function() { console.log('hello');}; m.set(hello, 'Hello ES6!') // Keys are functions m.get(hello) // Hello ES6!
Map Traversal methods
Map The native structure provides three iterator generating functions and one traversal method .
Map.prototype.keys(): Returns the traverser of the key name .Map.prototype.values(): The traverser that returns the key value .Map.prototype.entries(): Returns the traverser of all members .Map.prototype.forEach(): Traverse Map All members of .
Here's the thing to watch out for ,Map The traversal order of is the insertion order .
9、Proxy
Proxy Used to modify the default behavior of certain operations , It's equivalent to making changes at the language level , So it belongs to “ Metaprogramming ”(meta programming), That is to program the programming language .
Proxy Can be interpreted as , Set up a layer in front of the target object “ Intercept ”, External access to the object , All must be intercepted through this layer first , So it provides a mechanism , It can filter and rewrite external access .Proxy The original meaning of this word is agent , It's used here to show that it comes from “ agent ” Some operations , It can be translated into “ Agent ”.
var obj = new Proxy({
}, {
get: function (target, propKey, receiver) {
console.log(`getting ${
propKey}!`);
return Reflect.get(target, propKey, receiver);
},
set: function (target, propKey, value, receiver) {
console.log(`setting ${
propKey}!`);
return Reflect.set(target, propKey, value, receiver);
}
});
The above code sets up a layer of interception for an empty object , Redefined the reading of attributes (get) And set up (set) Behavior . The specific grammar will not be explained here for the time being , Just look at the running results . For objects with interception behavior set obj, To read and write its properties , You'll get the following results .
obj.count = 1
// setting count!
++obj.count
// getting count!
// setting count!
// 2
The above code shows ,Proxy In fact, overloading (overload) The dot operator , That is, it covers the original definition of language with its own definition .
ES6 Native offers Proxy Constructors , Used to generate Proxy example .
var proxy = new Proxy(target, handler);
Proxy All uses of objects , It's all in the form of , The only difference is that handler How to write parameters . among ,new Proxy() To generate a Proxy example ,target The parameter represents the target object to intercept ,handler Parameter is also an object , Used to customize interception behavior .
Here's another example of intercepting the behavior of reading properties .
var proxy = new Proxy({
}, {
get: function(target, propKey) {
return 35;
}
});
proxy.time // 35
proxy.name // 35
proxy.title // 35
In the above code , As constructor ,Proxy Take two parameters . The first parameter is the target object to proxy ( The above example is an empty object ), That is, if not Proxy Intervention , The original object to be accessed by the operation is ; The second parameter is a configuration object , For each agent's operation , You need to provide a corresponding processing function , This function will intercept the corresponding operation . such as , In the above code , The configuration object has a get Method , Used to intercept access requests to target object properties .get The two parameters of the method are the target object and the attribute to be accessed . You can see , Because the interceptor function always returns 35, So accessing any property will get 35.
Be careful , To make Proxy Work , Must be directed at Proxy example ( The example above is proxy object ) To operate , Instead of targeting ( The above example is an empty object ) To operate .
One technique is to put Proxy object , Set to object.proxy attribute , So that we can be in object Object .
var object = {
proxy: new Proxy(target, handler) };
边栏推荐
- Execution methods with static code blocks and child and parent classes
- Dynamic planning of force buckle punch in summary
- "Introduction to interface testing" punch in day08: can you save all parameters to excel for test data?
- Solve ''_ Xsrf 'argument missing from post
- Color space (1) - RGB
- Daily three questions 7.16
- 6.0 cancellation of member registration verification code
- mysql_ Account authorization permission recycling, account locking and unlocking, account creation and deletion
- mysql_ Create temporary table
- [stm32f103rct6] can communication
猜你喜欢

Ctfshow misc introduction

Application method and practical case of sqlmap of penetration test SQL injection

Wechat sports field reservation of the finished works of the applet graduation project (7) mid-term inspection report

Beginners must see the markdown User Guide

How to use blender to make 360 degree panorama and panoramic video?
![[stm32f103rct6] can communication](/img/24/71509bd0d74d43ce4a79b8126478ff.jpg)
[stm32f103rct6] can communication

JS foundation -- regular expression

Define macros in makefile and pass them to source code

mysql_ Record the executed SQL

PHP record
随机推荐
@Retryable @backoff @recover retry the use of annotations
"Introduction to interface testing" punch in to learn day07: websocket interface: how to test a completely unfamiliar protocol interface?
Riotboard development board series notes (VIII) -- building desktop system
Dc-2-range practice
Get to know string thoroughly
mysql_ Backup restore_ Specify table_ Backup table_ Restore table_ innobackup
Dynamic planning of force buckle punch in summary
# CF #808 Div.2(A - C)
Common Oracle commands
Mid year summary and personal feelings
Innobackupex parameter description
How to use blender to make 360 degree panorama and panoramic video?
JS foundation -- hijacking of this keyword
SQL Server 2022 installation
Study notes of filebeat
Function of each layer of data warehouse
"Introduction to interface testing" punch in to learn day09: Micro service interface: how to use mock to solve chaotic call relationships
Riotboard development board series notes (4) -- using Vpu hardware decoding
Learning record Xi
Analysis of FLV packaging