当前位置:网站首页>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] ]
边栏推荐
- Realize payment function in applet
- Charles+drony的APP抓包
- 单臂路由和三层交换的简单配置
- GSAP animation library
- Thread pool and singleton mode and file operation
- I feel cheated. Wechat tests the function of "size number" internally, and two wechat can be registered with the same mobile number
- [sword finger offer] 59 - I. maximum value of sliding window
- RISCV64
- 2022-07-04 matlab reads video frames and saves them
- [tpm2.0 principle and Application guide] Chapter 16, 17 and 18
猜你喜欢
Creative changes brought about by the yuan universe
[unity shader] insert pass to realize the X-ray perspective effect of model occlusion
SlashData开发者工具榜首等你而定!!!
行业案例|数字化经营底座助力寿险行业转型
Industry case | digital operation base helps the transformation of life insurance industry
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
Nunjuks template engine
The highest level of anonymity in C language
小试牛刀之NunJucks模板引擎
完整的电商系统
随机推荐
RIP和OSPF的区别和配置命令
Continuous test (CT) practical experience sharing
RISCV64
Kirk borne's selection of learning resources this week [click the title to download directly]
Flipping Game(枚举)
虚拟数字人里的生意经
[information security laws and regulations] review
直播预约通道开启!解锁音视频应用快速上线的秘诀
Golang client server login
企业展厅设计中常用的三种多媒体技术形式
【MIME笔记】
DeSci:去中心化科学是Web3.0的新趋势?
Embedded interview questions (algorithm part)
Short selling, overprinting and stock keeping, Oriental selection actually sold 2.66 million books in Tiktok in one month
高考填志愿规则
抢占周杰伦
学习open62541 --- [67] 添加自定义Enum并显示名字
testing and SQA_动态白盒測试[通俗易懂]
数据验证框架 Apache BVal 再使用
UVALive – 4621 Cav 贪心 + 分析「建议收藏」