In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-28 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)05/31 Report--
This article focuses on "what are the core features of es6". Interested friends may wish to take a look. The method introduced in this paper is simple, fast and practical. Let's let the editor take you to learn what are the core features of es6.
Es6 core features are: 1, use the Class keyword to create a class, and then instantiate the class to create an object; 2, the arrow function to simplify the callback function writing; 3, deconstruct assignment, according to a certain pattern, extract values from the array and objects, and assign values to variables; 4, "For … of" loop for traversing data, array, class array objects.
The operating environment of this tutorial: windows7 system, ECMAScript version 6, Dell G3 computer.
Core features of ES6
1. Class-like
ES6 formally enables the Class keyword to create "classes" and then instantiates "classes" to create "objects". The class abstracts the public part of the object, and a concrete object can be obtained by instantiating the class.
The first letter of the class name is capitalized.
The instantiated class must use the New keyword.
Simplify object-oriented encapsulation, inheritance, and polymorphism.
The keyword extends can be used to create a subclass.
The Constructor function of the class, which takes arguments and returns instance objects.
After the subclass inherits the parent class, it can call the method of the parent class or override the method of the parent class (precedence call).
The keyword super is used to access and call functions on the parent class of an object, both constructors and ordinary functions.
The Constructor function is automatically called when you create an instance using New. If you do not write this function, the class function will be generated automatically.
[note] when a subclass uses super in the constructor, it must be placed before this, that is, the constructor of the parent class is called first, and then the constructor of the subclass is used.
/ / 1. Use the Class keyword to create the class name {/ / own attribute constructor (formal parameter 1, formal parameter 2,.) {this. Attribute name 1 = formal parameter 1; this. Attribute name 2 = formal parameter 2;.} / / Common property init () {function body;}.} / / 2. Use the class combined with the New keyword to instantiate the object let Object = new class name (argument 1, argument 2,...); / / 3. Create a subclass class subclass extends class name {/ / own attribute (same as the parent class) constructor (formal parameter 1, parameter 2, new parameter 1.) {/ / super function calls the constructor super of the parent class (parameter 1, parameter 2,...); / / the new attribute of the subclass needs to be defined separately. New attribute 1 = new parameter 1;.} / / Common attribute (the subclass function is on its parent prototype, called first, and the parent function of the same name is on the upper prototype chain) init () {function body;}.}
2. Arrow function
The arrow function is used to simplify the writing of callback functions.
The simplified arrow function in the event needs to note that the this points to window.
Operation method: omit function, add = > between () and {}, simplex parameter omit (), single sentence function body omit {}, if single sentence is return statement, omit {} and return directly.
The arrow function can be used in conjunction with variable deconstruction.
Since curly braces are interpreted as code blocks, if the arrow function returns the object directly, it must be added outside the object. Put parentheses, otherwise an error will be reported.
Matters needing attention
The arrow function does not have its own this object.
The yield command cannot be used, so the arrow function cannot be used as a Generator function.
Cannot be treated as a constructor, that is, you cannot use the new command on the arrow function, otherwise an error is reported.
The arguments object cannot be used, which does not exist in the body of the function and can be replaced with the rest parameter.
The first case is the method that defines the object, and the method includes this inside.
The second situation is when dynamic this is needed, and the arrow function should not be used.
Inside the arrow function, you can also use the arrow function again. The following is a multiple nested function of the ES5 syntax.
3. Deconstruction assignment
Deconstruction assignment is to parse the structure and then assign values. ES6 allows you to extract values from arrays and objects and assign values to variables according to a certain pattern, which is called Destructuring, which belongs to "pattern matching". As long as both sides of the equal sign have the same pattern, the variable on the left will be assigned the corresponding value.
Array deconstruction assignment
An error will be reported if the data on the right side of the equal sign is an untraverable structure.
Complete deconstruction: if the structures on the left and right sides of the equal sign are exactly the same, the one-to-one corresponding assignment of the structure will be analyzed.
Incomplete deconstruction: the pattern to the left of the equal sign, which matches only part of the array to the right of the equal sign, can still be deconstructed successfully.
Deconstructing assignments allow you to specify default values. ES6 uses the strict equality operator (=) to determine whether there is a value at a certain location. Only array members strictly equal to the default value of undefined will take effect.
Object deconstruction assignment
If the deconstruction fails, the value of the variable is equal to undefined.
The object properties are out of order, but the variable must have the same name as the property to resolve to the correct value.
Object deconstruction can specify a default value, which takes effect only if the property value of the object is strictly equal to undefined.
When the object is deconstructed, because the JavaScript engine will understand {} as a code block, resulting in a syntax error, you need to put the whole deconstruction assignment statement in parentheses () to execute correctly.
String deconstruction assignment
Strings also support deconstruction assignments, where the string is converted to a class array object.
Class array objects all have a Length property, so you can deconstruct and assign values to this property.
Deconstruction assignment of function parameters
/ / function parameters support deconstructing assignment function sum ([x, y]) {return x + y;} / / when passing in parameters, the array parameters are deconstructed into x and ysum ([1,2])
Attention to the use of parentheses
The function argument disables parentheses.
The variable declaration statement disables parentheses.
Parentheses are disabled in the pattern matching part of the assignment statement.
Only the non-pattern matching part of the assignment statement, you can use parentheses.
4. For... Of cycle
Advantages, support Break,Continue and Return keywords, for-of loop is used to traverse data, array, class array objects.
Disadvantages: no subscript is provided, the original array cannot be modified, only the indexed array can be traversed, and the Hash array (objects) cannot be traversed.
For (value of arr) {perform the operation;}
Iterator
A new traversal mechanism with two cores.
An iterator is an interface that can quickly access data, create an iterator through Symbol.iterator, and get the iterative results through the iterator's next () method.
An iterator is a pointer used to traverse a data structure (similar to a database cursor)
5. Numerical addition method
Number.isInteger ()
Number.isInteger (), which is used to determine whether the value is an integer.
Returns false if the parameter is not a numeric value.
JavaScript internal integers and floating point numbers are stored in the same way, so 25 and 25 are considered the same value.
The JavaScript value is stored in a 64-bit double-precision format, and the numerical accuracy can reach up to 53 binary bits (1 hidden bit and 52 significant bits). If the numerical accuracy exceeds this limit, the 54 bits and the following bits will be discarded and the method will fail.
Math.trunc ()
The Math.trunc () method is used to remove the decimal part of a number and return the integer part.
For non-numeric values, Math.trunc () internally uses the Number method to convert it to numeric values first.
Returns NaN for null values and values that cannot intercept integers.
/ / low-version browser compatibility syntax Math.trunc = Math.trunc | | function (x) {return x < 0? Math.ceil (x): Math.f1oor (x);}
Math.sign ()
Math. The sign () method is used to determine whether a number is positive, negative, or zero.
If the parameter is a non-numeric value, it is automatically converted to a numeric value, and NaN is returned for a value that cannot be converted to a numeric value.
It returns five values: a positive parameter returns + 1, a negative parameter returns-1, a parameter of 0 returns 0, a parameter of-0 returns-0, and other values return NaN.
6. String addition method
Template string
Template strings are used to simplify string concatenation, and template strings support parsing variables, line breaks, and calling functions.
A template string (template string) is an enhanced string, identified by backquotes, and can be used as a normal string, to define multiline strings, or to embed variables in a string.
`text ${variable} text ${variable} text `
Includes (), startsWith (), endsWith ()
Includes (), which returns a Boolean value indicating whether the parameter string was found.
StartsWith (), which returns a Boolean value indicating whether the parameter string is at the header of the original string.
EndsWith (), which returns a Boolean value indicating whether the parameter string is at the end of the original string.
-[note] all three methods support the second parameter, which indicates where to start the search.
PadStart (), padEnd ()
ES2017 introduces the string completion length function, padstart () for header completion and padEnd () for tail completion.
Padstart () and padEnd () accept two arguments. The first parameter is the maximum length of string completion that takes effect. The second parameter is the string used for completion. If the second parameter is omitted, the space completion length is used by default.
If the length of the original string is equal to or greater than the maximum length, the string completion does not take effect and returns the original string.
If the sum of the length of the string used to complete and the original string exceeds the maximum length, the completion string that exceeds the number of digits is truncated.
The common use of padstart () is to specify the number of digits for numeric completion and can also be used to prompt for string format.
/ / complete length method prompts string format '12'.padStart (10,' YYYY-MM-DD'); / / "YYYY-MM-12"'08-31'.padStart (10, 'YYYY-MM-DD'); / / "YYYY-08-31"
TrimStart (), trimEnd ()
TrimStart () removes the spaces at the head of the string, and trimEnd () removes the spaces at the end of the string. They all return new strings and do not modify the original string. The two methods are also effective for invisible white space symbols such as the tab key and newline characters at the head (tail) of the string.
Repeat ()
The repeat method means that the original string is repeated n times to return a new string.
ReplaceAll ()
ES2021 introduces the replaceAll () method, which replaces all matches at once, uses the same as replace (), and returns a new string without changing the original string.
7. Add method to object
In ES6, variables can be written directly into the object, key is equivalent to the name of the variable, value is equivalent to the value of the variable, and value can be omitted directly, representing the complete properties of an object through key.
In addition to attributes that can be abbreviated, functions can also be abbreviated, that is, omitting the keyword function.
Object.is ()
It is used to compare whether the two values are strictly equal, and the behavior of the strict comparison operator (=) is basic.
Console.log (Object.is (+ 0,-0)) / / falseconsole.log (Object.is (NaN, NaN)); / / true
Object.assign ()
Object. The assign () method is used for merging objects, copying all enumerable properties of the source object (source) to the target object (target).
Obiect. The first parameter of the assign () method is the target object. The following parameters are source objects. Note that if the target object has an attribute with the same name as the source object, or more than one source object has an attribute with the same name, the following properties will override the previous properties.
8. Array adding method
Array.from ()
Array.from () is used to convert class array objects and traverable objects (including Set and Map) into real arrays.
The Array.from () method can also accept the second parameter, which acts like the array's map method, which is used to process each element and put the processed value into the returned array.
Array.of ()
Array.of () is used to convert an array of values.
Array. Of () returns an array of parameter values, or an empty array if there are no arguments.
This method can make up for the difference of the array constructor Array () because of the number of parameters.
Array.of () can basically replace Array () or new Array (), and there is no overload due to different parameters.
/ / compatible version of Arrayof () method function Arrayof () {return Array.prototype.slice.call (arguments);}
Fill () of the array instance
The fill () method populates an array with the given value.
It is very convenient for initializing empty arrays. All existing elements in the array will be erased.
Method supports the second and third parameters, which are used to specify the start and end positions of the fill.
If the populated type is an object, the object that is assigned is the object with the same memory address, not the deep copy object.
Find () of the array instance
Used to find the first qualified array member, and return undefined if it is not found.
FindIndex ()
Used to find the location of the first qualified array member, and return-1 if it is not found.
Includes ()
Indicates whether an array contains a given value and returns a Boolean value.
9. Let & Const
In ES6, in addition to global and local scopes, block-level scopes have been added.
Let
Syntax: let variable name = variable value
Let forbids repeating the declaration of the same variable within the same scope, so you cannot redeclare parameters within the function.
The variables declared by let are only valid within the code block where the let command is located, with {block-level scope}, does not cause declaration promotion, and can record the subscript that triggers the mouse event element.
Const
Syntax: const constant name = constant value
Constants do not take up memory space, and constant names are generally used in pure uppercase.
Const declares that variables must be initialized immediately and cannot be left to be assigned later.
The constant declared by const is only valid within the block-level scope, with {block-level scope}, and will not cause declaration to be promoted. There is also a temporary dead zone, and repeated declaration of the same constant is prohibited, and the constant value cannot be changed.
The variable declared by const can guarantee that the memory address of the variable remains unchanged, which is equivalent to a constant for simple type data. For reference type data, you can only ensure that the pointer to the actual data in the memory address remains the same, but not the data structure. Declaring objects as constants requires special attention!
Temporary dead zone
Temporary dead zone (TDZ) A grammatical rule in which internally declared variables are "bound" to the area as long as there is a let or const command in the block scope, forming a closed scope, that is, variables within the code block must be declared before they are used.
10. Modular development
For division of work and cooperation, each js is a module, each engineer can develop his own module independently, and the main module finally introduces and calls
1. The sub-module should be exposed publicly.
Export var obj= {}
2. The main module is introduced and used
Import {obj as alias} from ". / File path"
3. When introducing a HTML page, you need to change type to module.
The function of ES6 module is mainly composed of two commands, export and import,export are used to specify independent external interfaces, import is used to input functions provided by other modules, a module is an independent file, and the type of the script tag of the introduction module should be set to module.
11. Extension operator & Rest operator
Extension operator and Rest operator are added to ES6, which can solve the coding problem when the function parameters and the length of array elements are unknown, and make the code more robust and concise.
Extension operator
The extension operator is represented by three dots.
Purpose: converts an array or class array object to a comma-separated sequence of values, the basic use of which is to disassemble arrays and strings.
/ / 1. The extension operator replaces the apply () function to get the maximum value of the array let arr = [1, 4, 2, 5, 3]; / / apply () method Math.max.apply (null, arr); / / extension operator method Math.max (.. arr); / / 2. The extension operator replaces the concat () function to merge the array let arr1 = [1,2,3]; let arr2 = [4,5,6]; / / concat () method arr1.concat (arr2); / / extension operator method [. Arr1,... arr2]
Rest operator (remaining parameters)
The Rest operator is represented by three dots.
Function: contrary to the extension operator, it is used to convert a comma-separated sequence of values into an array.
When deconstructing using the rest operator, the variable corresponding to the res operator must be placed in the last place, otherwise the variable cannot recognize how many numeric values are read and an error will be thrown.
The argument to a function is a comma-separated sequence of values that can be converted to an array using the rest operator instead of arguments.
/ / the combination of 1.Rest operator and deconstruction uses the split fraction group let arr = [1, 2, 3, 4, 5]; / / split the array with the first element assigned to arr1, and the remaining elements assigned to arr2let [arr1,... arr2] = arr;// to split the array, the first two elements are assigned to arr1 and arr2, and the remaining elements are assigned to arr3let [arr1, arr2,... arr3] = arr. The / / 2.Rest operator replaces argumentsfunction sum (... arg) {/ / gets the shape parameter group console.log (arg);} / / passes in the formal parameter sum (formal parameter 1, formal parameter 2,.)
Distinguish between two operators
The extension operator and the rest operator are inverse operations to each other. The extension operator divides the array into independent sequences, while the rest operator combines the independent sequences into a single array.
When three points appear on the function parameter or to the left of the assignment equal sign, it is the rest operator.
When three points appear on the argument of the function or to the right of the equal sign of the assignment, it is the extension operator.
Expand | differences among Let, Var and Const
Let declared variables, there is a block-level scope, there is no variable promotion, the value can be changed.
Var declared variables, there is a function scope, there is a variable promotion, the value can be changed.
The constant declared by Const has a block-level scope and the value cannot be changed.
Extension | there are five ways for ES6 to traverse object attributes
For... In
For... In is used to traverse the object and itself and inherited enumerable properties (excluding the Symbol property).
Object.keys (obj)
The Object.keys () function returns an array containing all the enumerable properties of the object itself, excluding inherited properties and Symbol properties.
Reflect.ownKeys (obj)
The Reflect.ownKeys (obj) function returns an array that can contain enumerated properties, non-enumerable properties, and Symbol properties, and does not contain inherited properties.
Object.getOwnPropertyNames (obj)
The Object.getOwnPropertyNames (obj) function returns an array of enumerable and non-enumerable properties of the object itself, without inheritance and Symbol properties.
Object.getOwnPropertySymbols (obj)
The Object.getOwnPropertySymbols (obj) function returns an array containing all the Symbol properties of the object itself, but no other properties.
At this point, I believe you have a deeper understanding of "what are the core features of es6?" you might as well do it in practice. Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!
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.