当前位置:网站首页>ES6 note 1
ES6 note 1
2022-07-07 19:06:00 【Thinking about getting rich every day】
Catalog
One let Variable declaration and properties
3、 ... and Deconstruction and assignment of variables
6、 ... and Default value settings for function parameters
One let Variable declaration and properties
//1. Variables cannot be declared repeatedly
/*
// error
let star=' Lolo ';
let star=' Piglets ';
// Sure
var star=' Lolo ';
var star=' Piglets ';
*/
//2. Block level scope overall situation , function ,eval
//if else while for Inside { }
/*
{
// error : let girl=' Week week ';
// correct : var girl=' Week week ';
}
console.log(girl)
*/
//3. No variable promotion
/** error
* console.log(song);
* let song=' A tourist ';
*/
// Does not affect the scope chain
{
let school=' hengshui ';
function fn(){
console.log(school);
}
fn();
}
Two const Declare constant
characteristic :
1 Be sure to assign the initial value
2 General constants use uppercase
3 The value of a constant cannot be modified
4 Block level scope
5 For the element modification of arrays and objects , It cannot be counted as a modification of constants , No mistake. ( When const When the decorated constant is an array or object , As long as the address pointed to by the constant does not change , You can't report an error )
3、 ... and Deconstruction and assignment of variables
Four Template string
5、 ... and Arrow function
(1) Arrow function declaration features
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title> Arrow function </title>
</head>
<body>
<script>
//ES6 Allow to use [ arrow ](=>) Defined function
// Declare a function
let fn=(a,b)=>{
return a+b;
}
// Call a function
let result=fn(1,2);
console.log(result);//3
//1. In the arrow function this Is static ,this Always point to... Under the scope where the function is declared this value
function getName(){
console.log(this.name);
}
let getName2=()=>{
console.log(this.name);
}
window.name=' Second middle school ';
const school={
name:"ERZHONG"
}
// Call directly :this Point to window
getName();// Second middle school
getName2();// Second middle school
//call Method call
getName.call(school);//ERZHONG
getName2.call(school);// Second middle school
//2. Cannot instantiate an object as a construct
/* // Report errors
let Person=(name,age)=>{
this.name=name;
this.age=age;
}
let me=new Person('xiao',30);
console.log(me);
*/
//3. Out of commission arguments Variable
/*fn Report errors
let fn=()=>{
console.log(arguments);
}
fn(1,2,3);*/
//4. Shorthand for arrow function
//1) Omit parentheses , When there is only one formal parameter
let add=n=>{
return n + n;
}
console.log(add(9));//18
//2) Omit the curly brackets , When there is only one statement in contemporary code body , here return Must omit , And the execution result of the statement is the return value of the function
let pow=n=>n*n;
console.log(pow(8));//64
</script>
</body>
</html>
(2) Application scenarios : The arrow function is suitable for this Unrelated callbacks . Timer , Array method callback
The arrow function is not suitable for this About callbacks . Event callback , Object method
6、 ... and Default value settings for function parameters
1. Parameter whose initial value has a default value , The general position depends on the back ( Hidden rules )
function add(a,b,c=10) {
return a+b+C;
}
let result = add(1,2);
console. log(result);//13
2. Combined with deconstruction assignment
function connect ({host=" 127.0.0.1", username, password, port}){
console. log(host)//baidu.com
console . log(username)//root
console .1og(password)//root
console. log(port)//3306
}
connect({
host:'baidu.com',
username :'root',
password:'root' ,
port: 3306
})
7、 ... and rest Parameters
ES6 introduce rest Parameters , To get arguments to a function , Used in place of arguments
ES5 How to get arguments
function date(){
console. log(arguments);// It's not an array, it's an object
}
date(' Angelica dahurica ',' Gillian ',' Sihui ');
//rest Parameters
function date(...args){
console. log(args);// The output is an array, not an object
}
date(' Gillian ',' Baizhi ',' Sihui ');
rest The parameter must be placed at the end of the parameter
8、 ... and Extension operator
... The extension operator can convert an array into a comma separated sequence of parameters
application :
//1. Merging of arrays
const kuaizi=[' Wang Taili ',' Xiao Yang '];
const fenghuang=[' Zeng Yi ',' Linghua '];
const zuhe=[...kuaizi,...fenghuang];
console.log(zuhe);//Array(4) [ " Wang Taili ", " Xiao Yang ", " Zeng Yi ", " Linghua " ]
//2. Clone of array
const sanzhihua=['E','G','M'];
const sanyecao=[...sanzhihua];
console.log(sanyecao);//Array(3) [ "E", "G", "M" ]
//3. Convert a pseudo array to a real array
//querySelectorAll() Method returns the match specified in the document CSS All elements of the selector
const divs=document.querySelectorAll('div');
console.log(divs);// object
const divArr=[...divs];
console.log(divArr);// Array
Nine Symbol
1 Introduce and create
ES6I A new type of raw data is introduced Symbol, Represents a unique value . It is JavaScript The seventh data type of language , It's one . A data type similar to a string .
Symbol characteristic :
1) Symbol Is unique , Used to resolve naming conflicts
2)Symbol Value cannot be calculated with other data
3) Symbol Defined object properties cannot be used for..in Loop traversal , But you can use Reflect.ownKeys/ Object.getOwnPropertySymbols()
To get all the key names of the object
// establish Symbol
let s = Symbol();
console.log(s, typeof s);//Symbol() symbol
//Symbol() Defined values are not placed in the global symbol The registry , Every time it's new , Even if the description is the same, the values are not equal ;
let s2 = Symbol(' Tea ah No.2 Middle School ' );
let s3 = Symbol(' Tea ah No.2 Middle School ' );
console.log(s2);//Symbol(" Tea ah No.2 Middle School ")
console.log(s2===s3);//false
//Symbol. for establish
let s4 = Symbol. for(' Tea ah No.2 Middle School ');
let s5 = Symbol. for(' Tea ah No.2 Middle School ');
//Symbol for( Method will be based on the given value , From runtime symbol Find the corresponding... In the registry symbol. If you find it , Then return it ,
// Otherwise, create a new symbol, And put it in the overall situation symbol Registration form application .
console.log(s4===s5);//true
// Cannot operate with other data
/* data type
USONB
// u undefined
// s string、symbol
//o object
// n nul1 number
// b boolean
*/
2 Use scenarios
<script>
// Add methods to objects uo down
// The first method
let game={
name:"zhangsan",
up:function(){console.log("1")},
down:function(){console.log("2")},
};
let methods={
up:Symbol(),
down:Symbol()
};
game[methods.up]=function(){
console.log(" well ");
}
game[methods.down]=function(){
console.log(" Hello ");
}
console.log(game);//Object { name: "zhangsan", up: up(), down: down(), Symbol(): methods.up(), Symbol(): methods.down() }
// The second method
let youxi={
name:" Werewolf killing ",
[Symbol('say' )]: function(){
console.log(" I can speak ")
},
[Symbol(' zibao' )]: function(){
console. log(' I can explode ' );
}
}
console.log(youxi);//Object { name: " Werewolf killing ", Symbol("say"): say(), Symbol(" zibao"): zibao() }
console.log(Object.getOwnPropertySymbols(youxi));//Array [ Symbol("say"), Symbol(" zibao") ]
console.log(Reflect.ownKeys(youxi));//Array(3) [ "name", Symbol("say"), Symbol(" zibao") ]
</script>
3 Built in values ( Are used as attributes of an object type )
Symbol.hasInstance : When other objects use instanceof Operator , When judging whether it is an instance of the object , Will call this method
Symbol.isConcatSpreadable: Object's Symbol.isConcatSpreadable Property equals a cloth
Er value , Indicates that the object is used for Array.prototype.concat() when , Can I expand .
Symbol.unscopables: This object specifies the use of with When a keyword , Which attributes will be with Environmental exclusion .
Symbol.match: When executed str.match(myObject) when , If the attribute exists , It will call it. , Returns the return value of the method .
Symbol.replace: When the object is str.replace(myObject) Method call , Will return the return value of the method .
Symbol.search: When the object is str. search (myObject) Method call , Will return the return value of the method .
Symbol.split: When the object is str. split (myObject Method call , Will return the return value of the method .
Symbol.iterator: Object to carry out for...for loop , Would call Symboliterator Method , Returns the default traversal of the object
Symbol.toPrimitive: When the object is converted to a value of the original type , Will call this method , Returns the original type value of the object .
Symbol. toStringTag: Call... On this object toString When the method is used , Returns the return value of the method
Symbol.species: When creating the generation object , Will use this property
Symbol.hasInstance:
class Person{
//static There are automatic usage scenarios
static[Symbol.hasInstance](param){
console.log(param);//Object { }
console.log(" I was used to monitor the type ");
//return true// When judging the type, return true
return false;// When judging the type, return false
}
}
let o={};
console.log(o instanceof Person);//false
Symbol.isConcatSpreadable:
const arr = [1,2,3];
const arr2 = [4,5,6];
arr2[Symbol.isConcatSpreadable] = false;
console.log(arr. concat(arr2));//Array(4) [ 1, 2, 3, [4,5,6] ]
边栏推荐
- 线程池中的线程工厂
- How to choose the appropriate automated testing tools?
- 【HDU】5248-序列变换(贪心+二分)「建议收藏」
- Cloud security daily 220707: Cisco Expressway series and telepresence video communication server have found remote attack vulnerabilities and need to be upgraded as soon as possible
- 伺服力矩控制模式下的力矩目标值(fTorque)计算
- 单臂路由和三层交换的简单配置
- Tsinghua, Cambridge and UIC jointly launched the first Chinese fact verification data set: evidence-based, covering many fields such as medical society
- Static routing configuration
- 6. About JWT
- C语言中匿名的最高境界
猜你喜欢
Short selling, overprinting and stock keeping, Oriental selection actually sold 2.66 million books in Tiktok in one month
【软件测试】从企业版BOSS直聘,看求职简历,你没被面上是有原因的
能同时做三个分割任务的模型,性能和效率优于MaskFormer!Meta&UIUC提出通用分割模型,性能优于任务特定模型!开源!...
[tpm2.0 principle and Application guide] Chapter 16, 17 and 18
Review of network attack and defense
CVPR 2022 - learning non target knowledge for semantic segmentation of small samples
虚拟数字人里的生意经
Creative changes brought about by the yuan universe
线程池和单例模式以及文件操作
String type, constant type and container type of go language
随机推荐
Will domestic software testing be biased
[information security laws and regulations] review
Cadre de validation des données Apache bval réutilisé
脑洞从何而来?加州大学最新研究:有创造力的人神经连接会「抄近道」
testing and SQA_动态白盒測试[通俗易懂]
CVPR 2022丨学习用于小样本语义分割的非目标知识
咋吃都不胖的朋友,Nature告诉你原因:是基因突变了
UVALive – 4621 Cav 贪心 + 分析「建议收藏」
【Unity Shader】插入Pass实现模型遮挡X光透视效果
The performance and efficiency of the model that can do three segmentation tasks at the same time is better than maskformer! Meta & UIUC proposes a general segmentation model with better performance t
低代码助力企业数字化转型会让程序员失业?
How many times is PTA 1101 B than a
Industry case | digital operation base helps the transformation of life insurance industry
IP netns command (memo)
DeSci:去中心化科学是Web3.0的新趋势?
3.关于cookie
What is the general yield of financial products in 2022?
[Blue Bridge Cup training 100 questions] sort scratch from small to large. Blue Bridge Cup scratch competition special prediction programming question centralized training simulation exercise question
Idea completely uninstalls installation and configuration notes
Complete e-commerce system