当前位置:网站首页>Notes on learning Es5 and ES6
Notes on learning Es5 and ES6
2022-06-11 07:05:00 【Boiled wine cos】
List of articles
ES5 grammar
Strict mode
Must use var Life variable
It is forbidden to use... In custom functions this Point to window object
establish eval Scope
var str = 'NBA';
eval('alert(str)')
// Can parse the string inside and execute
// but eval The variables in are automatically promoted to the global level
// So use the strict pattern , take eval Created scope , Into the private
- Objects cannot have properties with duplicate names
Json object
json.stringfy(obj/arr)
// Convert an object or array to json object
json.parse(json)
// Empathy
- json It's a format for transmitting data
- You can easily get the properties of the object
object package
object.create(prototype ,[descriptors]) obj ={ username : 'jjr', age:'1'} var obj1={ } obj1 =object.create(obj, { sex:{ value:'boy'// Actual specified value writeable:true// Can I modify , The default is faluse configurable:true// Can it be deleted , The default is faluse-- delete obj1.sex enumerable:true// Identify whether the attribute can be used for in To enumerate The default is false //for(var i in obj1){ //console.log(i) Will it sex attribute //} } } )object.defineproperties(obj,description) // Used to extend attributes var obj ={ username : 'jjr', age:'1'} object.defineproperties(obj, { fullname:{ get:function(){ return this.username + " " +this.age; } // This is how to get the value of the attribute set:function(data){ // Listening extended properties , Automatically called when the extended attribute callback , Inject the changed value as an argument }get propertyname(){ } // The callback function used to get the current property value set propertyname(){ } // Callback function used to monitor the current property value change
array Extension of arrays
indexOf(value) take value The first subscript appears
lastindexof() take value The last subscript appears
foreach((item , index)=>{}) Traversal array
map((item , index)=>{}) Can return a new array ( More than traversal )
filter((item , index)=>{}) Can return a new array
Function extension
binding obj use call and apply
var obj={username : 'jjr', age:'1'}
function foo(data){
consolo.log(this,data)
}
foo.call(obj) Can be bound
foo.apply(obj)
It is the same without parameters
foo.call(obj,33)
// Start directly with the second parameter , One by one
foo.apply(obj,[33])
// The second one must be the array passed in to be placed in the array
foo.blind(obj)
blind() Is to return the function to , The current function will not be called immediately
So there is var bar = foo.blind(obj)
There's more bar(data)
Can be combined
foo.blind(obj ,33)()
Callback function : Not called immediately , So want to use blind
ES6 grammar
const and let
- Valid in block level scope
- Can not repeat the statement
- No preprocessing , There is no block level promotion
- stay for Use... In circulation let
- Use let replace var Is the trend
Click the callback function , In the practice queue , Check "execute" after finishing in the main queue // You can avoid using closures
- Do not modify
- Other features are the same as let
- Save data that doesn't need to be changed
- If it's an object , The value of the attribute can be changed , But the name and number of attributes cannot be changed
Deconstruction and assignment of variables
Extract data from an object or array , And assign to variable ( Multiple )
Object's deconstruction assignment
let {n,a}={n:'tom',a:12} // Must be an existing attribute let {n:newa,a}={n:'tom',a:12} // Change of name You can take the data directly let {n}={n:'tom',a:12}//n:'tom' let {a}={n:'tom',a:12}//a:12Deconstruction and assignment of arrays
let [a,b]=['tom',12] // You can't take the data directly // Make room for it let [,,,a,b]=[1,2,3,4,5]//a=4,b=5 let [,,a,b]=[1,2,3,4,5]//a=3,b=4 let [,,...a]=[1,2,3,4,5]//a=[3,4,5] // The ellipsis must be the lastpurpose : Assign values to multiple formal parameters
var obj={username : 'jjr', age:'1'} function foo({username,age}){ consol.log(username,age) } foo{obj}
Template string
- Simplify string splicing
- Template string must use `` contain
- The changed part must be $(XXX) Definition
let obj={
username:'kobe',age:39}
let str = ' My name is '+obj.usename+', My age this year is '+obj.age
let str1 = ` My name is $(obj.usename), My age this year is $(obj.age)`
Simplified objects obj Internal writing
Omit attribute values of the same name
Omit the of the method function
let x=1; let y=2; let point ={ x, y, setX(x){ this.x=x} } let point1 = { x:x, y:y,// The original way of writing // Therefore, attributes with the same name can be left blank getx:function(){ // It can be omitted :function return this.name; } // It can be changed into the following mode getx(){ return this.name; } }
Arrow function
effect : Defining anonymous functions
No parameters :()=>console.log(‘xxx’)
The case of a parameter i=>i+2
Greater than one parameter (i,j)=>i+j
When the function body does not use braces, it returns the result by default
If the function has multiple statements ( That is, when there are braces ){}, If there is something to return , Manual return required
Usage scenarios are often used to define callback functions
characteristic
concise
Arrow function does not have its own this, Arrowhead function this What is not called is determined by , But the object in which it is defined is its this
Of a regular function this That is, whoever calls it will use it
Expand your understanding of : Arrowhead function this See if there's a function in the outer layer If there is , Of outer functions this It's the function of the inner arrow this without , be this yes window
let fun = function (){
console.log('arrow')
}
let fun1 = () =>console.log('arrow');
fun1()
let fun2 = a =>console.log('a');
fun2('aaa')
let fun3 = (a,b) =>console.log(a,b);
fun3(25 ,26)
let fun3 = (a,b) =>{
console.log(a,b);
return a+b;
}
let fun4 = (a,b) =>a+b;
let sum = fun4(25 ,26)
// No, return Words , The return value defaults to undefined
Three point operator
Also called … Operator
reset Variable parameters , The position of the parameter
The three-point operator can only be collected at the end (in function)
function fun(a,...values){ console.log(arguments); //arguments.forEach(function //(item,index){ //console.log(item,index) //}) so arguments Is a pseudo operator // also callee Self callback method of console.log(values); values.forEach(function (item,index){ console.log(item,index) }) // A true array can use the array method } fun(1,2,3)Extension operator , Actual parameters
It is equivalent to traversing the array and getting each value
let arr1 = [1,3,5] let arr2 = [2 ,...arr1,6] arr.push(...arr1)
Parameter defaults
When no parameter is passed in, the default value in the formal parameter is used by default
function point(x = 1,y = 2){
this.x=x;
this.y=y
}
let point = new point(23,35);//x=23,y=35
let point1 = new point(35);//x=35,y=2
let point1 = new point();//x=1,y=2
promise object
symbol
Original data type (string, number, Boolean ,null, undefined , object )
symbol Is a newly added data type
symbol The value of the property is unique , Solve the problem of naming conflict
symbol Value cannot be calculated with other data , Including the same string splicing
for in and for of It doesn't traverse symbol attribute
Use
call symbol Function to get symbol value
establish symbol Property value let symbol = Symbol(); Unwanted new console.log(symbol)//symbol()The reference mark
let symbol1 = Symbol('one') let symbol2 = Symbol('two') console.log(symbol1,symbol2) //Symbol(one) Symbol(two)Symbol Types can also be used to define a set of constants , Make sure that the values of these constants are not equal .
built-in symbol value
In addition to defining what you use Symbol Unexpected value ,es6 It also provides 11 Built in Symbol value , Point to the internal usage of the language
Symbol.iterator
Object's Symbol.iterator attribute , Point to the default iterator method with the object ( Later on )
let obj ={
username :'kobe' ,age:39}
obj[symbol] = 'hello'
console.log(obj)
//Symbol():'hello'
const mySymbol = Symbol();
const a = {
};
a.mySymbol = 'Hello!';
a[mySymbol] // undefined
a['mySymbol'] // "Hello!"
// In the above code , Because the dot operator is always followed by a string , So it won't read mySymbol The value referred to as the identity name , Lead to a The property name of is actually a string , Instead of a Symbol value .
// actually JavaScript All properties of an object are strings , But the value of the property can be any data type .
// Empathy , 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]: function (arg) {
... }
};
obj[s](123);
Iterator Iterator
- iterator( Iterator means ) It's an interface mechanism , Provide a uniform for different data structures Access mechanism
- effect
- Provide a unified framework for all kinds of data structures , Simple access interface
- Enables members of a data structure to be arranged in a certain order
- es6 Creates a new traversal command for of loop ,iterator Interfaces are mainly used to attack for of Use
- working principle
- Create a pointer object ( Traverser object ), Point to the actual location of the data structure
- First call next Method , The pointer automatically points to the first member of the data structure
- Next, every time you call next Method , The pointer will go all the way back , Know to point to the last member
- Each one is used next Method returns a containing value and done The object of
- value: The value of the current member
- done: Boolean value
- value The value that identifies the current member , The Boolean value corresponding to dong'a indicates whether the current data structure has been traversed
- When the traversal is over, it returns value yes undefined,done The value is false
- Original possession iterator Interface data ( It can be used for of Let's do the traversal )
- Expand your understanding of
- When deployed on the data structure symbol.iterator When the interface of , This data can be used to for of Traverse
- When using for of When traversing the target data structure , The data will automatically go to symbol.iterator attribute
- symbol.iterator Property points to the object's default iterator method
- array
- arguments
- set Containers
- map Containers
function myIterator(arr){
let nextIndex=0
return {
// Traverser object
next:function(){
return {
nextIndex <arr.length ? {
value:arr[nextIndex++],done:false} : {
value:undefined done:true}
}
}
}
}
// Prepare a data
let arr = [1,4 7,'abc']
let iteratorObj=myIterator(arr);
iteratorObj.next();
iteratorObj.next()
The above will be es6 Add to data type in advance
take iterator Interface is deployed to the specified data type , You can use for of Loop traversal
Already exist ( Array , character string ,arguments,set and map Containers )
let arr = [1,4 7,'abc']
for(let i of arr){
console.log(i)
}
let str = 'abcde'
for(let i of str){
console.log(i)
}
function fun(){
for(let i of arguments){
console.log(i)
}
//arguments It's a pseudo array , General methods without arrays , So there was no for each Method
}
fun(1,4,5,'abc')
There is no deployment on the object iterator, So it can't be used for of Method to traverse
When using the three-point operator and deconstruction assignment, you use by default iterator Interface
let arr2=[1,6]
let arr3=[1,...arr2,6]
// Ergodic arr2 Value
Isomorphic deconstruction assignment
Closure
Concept
Closure function : Functions declared in a function , It's called a closure function .Closure : Internal functions always have access to the parameters and variables declared in the external function in which they reside , Even if the external function is returned ( End of life ) After that .
characteristic
Make it possible for external access to function internal variables ;
Local variables are resident in memory ;
You can avoid using global variables , Prevent contamination of global variables ;
Memory leaks can occur ( There's a block of memory that's been occupied for a long time , Without being released )
Closure creation :
Closure is to create a separate environment , The environment inside each closure is independent , Mutual interference . Closures leak memory , Every time an external function executes Hou , The reference address of the external function is different , Will create a new address . However, the current active object contains data referenced by an internal subset , So at this point , This data is not deleted , Keep a pointer to the internal active object .
————————————————
Copyright notice : This paper is about CSDN Blogger 「 Second brother Yang 」 The original article of , follow CC 4.0 BY-SA Copyright agreement , For reprint, please attach the original source link and this statement .
Link to the original text :https://blog.csdn.net/weixin_43586120/article/details/89456183
Symbol.Interator
It is equivalent to deploying on the specified data structure iterator Interface
When using for of To traverse a data structure , First of all Symbol.Interator, If you find it, go through it , You can't traverse without (obj is not iterator)
let targetData={
[Symbol.Interator]:function(){
let nextIndex=0
return {
// Traverser object
next:function(){
return {
nextIndex <this.length ? {
value:this[nextIndex++],done:false} : {
value:undefined done:true}
}
}
}
}
}
Generator function
es6 One of the solutions to a problem
generator Function is a state machine , It encapsulates data in different states
Used to generate the traverser object
Pause function ( Lazy evaluation ),yield Can pause ,next Method can start , Every time I return yield The result of the expression after
characteristic
function There is a model number between and the function name
For internal use yield Expressions to define different states
function * generatorExample(){ let result = yield 'hello'// The status value is hello //result The value is undefined, namely yield Return to normal will be undefined // But there are next( value ) Will be sent back yield 'generator'// The status value is generator }generator Function execution returns a pointer object ( Traverser object )( yes iterator), Instead of executing the logic inside the function
call generator The return value of the function next When the method is used , The logic inside the function begins to execute , encounter yield The expression stops , return {value:yield The expression after / The return value of the execution result of the statement /undefined,done:false/true( Traversal complete )}
Call again next Method will stop from the last time yield Start at , Until the last
function * myGenerator(){
console.log(' Start execution ')
yield 'hello'// state hello
console.log(' After suspension , Carry on ')
yield 'generator'// state generator
}
let MG = myGenerator()
// Returns a pointer object
//MG.next()
console.loge(MG.next())
//{value:hello,done:false}
let obj={
uername:'jjr',age:'18'}
obj[Symbol.interator]=function*mygenerator(){
yield 1;
yield 2;
yield 3;
}
for(let i of obj){
console.log(i)
}
//1 2 3
function getNews(url){
$.get(url,function(data){
console.log(data// Data obtained )
let url=''+data. data
SX.next(url)
})//jquery method import
}
function * sendXml(){
let url=yield getNews( website )
yield getNews(url)
}
let SX = sendXml();
SX.next();
async function (ES7)
To solve the problem of asynchronous callback in a real sense , Synchronous process to express the operation of a department
The essence :genenrator The grammar sugar of ( Give Way generator The method is more perfect )
grammar
async function foo(){ await // Asynchronous operations // Wait until the asynchronous operation is completed , Carry out the next await // Asynchronous operations }characteristic
- No need to be like generator Function to call next Method , encounter await wait for , When the current operation is completed, it will be executed
- It's always going back to promise object , It can be used then Method to proceed to the next step
- async When replaced Generator Asterisk of function ,await Replaced Russian Generator Of yield
- More semantically clear , Easy to use , No side effects and adverse reactions
async function foo(){
return new Promise(resolve=>{
setTimeout(function(){
resolve()
},2000)
setTimeout(resolve,2000)
})
}
async function test(){
console.log('begin',new Date().toTimeString)
await foo()
// There is no need to next, Automatically
console.log('end',new Date().toTimeString)
}
await The return value of
function teat2() { return 'xxx' } async function asyncPrint(){ let result = await teat2() console.log(result) } asyncPrint() //"xxx"async function asyncPrint(){ let result = await Promise.resolve('promise'); console.log(result) result = await Promise.reject('fail') console.log(result) } asyncPrint() //promise // Uncaught (in promise) fail
class
- adopt class Defining classes , Implementation class inheritance (js We inherited from the prototype )
- Pass in the class constructor() Define construction method
- adopt new Create the real column of the class
- adopt extends Implementation class inheritance
- adopt super() Call the constructor of the parent class
- Override the general methods inherited in the parent class
class Person {
constructor(name,age){
this.name=name;
this.age=age
}
// Class
showName(){
console.log(this.name)
}
// On the prototype of the real column object , Not on the object itself
}
let person = new Preson('kobe',39)
class starPerson extends Person(){
constructor(name,age,salary){
super(name,age)
// Identifies the constructor that calls the parent class
//this.name=name;
//this.age=age
// Follow java equally
this.salary = salary
}
showName(){
console.log(this.name,this.age,this.salary)
}
// Method coverage / Override of the method of the parent class
}
- Pass in the class constructor() Define construction method
- adopt new Create the real column of the class
- adopt extends Implementation class inheritance
- adopt super() Call the constructor of the parent class
- Override the general methods inherited in the parent class
class Person {
constructor(name,age){
this.name=name;
this.age=age
}
// Class
showName(){
console.log(this.name)
}
// On the prototype of the real column object , Not on the object itself
}
let person = new Preson('kobe',39)
class starPerson extends Person(){
constructor(name,age,salary){
super(name,age)
// Identifies the constructor that calls the parent class
//this.name=name;
//this.age=age
// Follow java equally
this.salary = salary
}
showName(){
console.log(this.name,this.age,this.salary)
}
// Method coverage / Override of the method of the parent class
}
边栏推荐
- Janus feature草稿
- 教育专家王中泽老师一招解决学生问题
- webserver
- Completed in May, 22
- Starting from scratch (IV) enemy aircraft flying out of the border disappear automatically
- Aircraft battle from scratch (III) flight between player aircraft and enemy aircraft
- Error occurred in pycharm DeprecatedEnv: Env FrozenLake-v0 not found (valid versions include [‘FrozenLake-v1‘])
- Shuttle container component
- 开源漫画服务器Mango
- AppClips&Tips(持续更新)
猜你喜欢

Whether the ZABBIX monitoring host is online

About the designer of qtcreator the solution to the problem that qtdesigner can't pull and hold controls normally
![[matlab WSN communication] a_ Star improved leach multi hop transmission protocol [including source code phase 487]](/img/fd/53776b550390752282cd8797193436.png)
[matlab WSN communication] a_ Star improved leach multi hop transmission protocol [including source code phase 487]

Explain the difference between void 0 and undefined

.NET C#基础(6):命名空间 - 有名字的作用域

Difference between byte and bit

Do you use typescript or anyscript

Implementation of customization function page of online Fox game server room configuration wizard service
![[Xunwei dry goods] opencv test of Godson 2k1000 development board](/img/94/312bb1f0d5e8d49506f659ad23cd3a.jpg)
[Xunwei dry goods] opencv test of Godson 2k1000 development board

The difference between arrow function and ordinary function
随机推荐
Summary of string processing skills III
pycharm出现error.DeprecatedEnv: Env FrozenLake-v0 not found (valid versions include [‘FrozenLake-v1‘])
[并发进阶]——线程池总结
Transformer Tracking
Nodejs database (Part 2)
【Matlab图像加密解密】混沌序列图像加密解密(含相关性检验)【含GUI源码 1862期】
Matplotlib,设置坐标刻度大小,字体/设置图例大小及字体/设置纵横坐标名称及字体及大小
一、SQLServer2008安装(带密码)、创建数据库、C#窗体项目测试
SQL language - query statement
Leetcode hot topic 100 topic 21-25 solution
First day of database
Grayscale publishing through ingress
Quality-aware Feature Aggregation Networkfor Robust RGBT Tracking
About the designer of qtcreator the solution to the problem that qtdesigner can't pull and hold controls normally
Object. Specific implementation and difference between create() and new
Library management system 1- project approval
Web API、DOM
数学方法论的含义和研究意义
Flutter Container组件
1266_FreeRTOS调度器启动代码实现分析