During this time, I learned some basic syntax and applications after watching the basic JavaScript tutorial reported by Xiaozhou of station b. the goal of the next stage is to try to complete some small modules containing three major pieces.
Function summary
Function declaration
A declaration can be called multiple times
Promotion of function declaration
The declaration of the function can be used later
Anonymous function
Anonymous functions are usually used as arguments
setInterval(funcion(){ console.log("hello") },1000)
Function expression
const fun=function(n,m){ return n+m; } let res=fun(10,20);
Difference between function expression and function declaration: function expression does not have the feature of function promotion
method
Methods are functions that belong to an object
const cat ={ name:"miaomiao", sayName:function(){ console.log(this.name) } //Abbreviation method sayName(){ console.log(this.name) } } cat.sayName();
Default parameters
function fun(n=100,m=200){ return n+m; } let res=fun();//300 res=fun(10);//210 res=fun(10,20);//30
Execute function now
Call directly after declaration; Cannot be called more than once
(function(){ var a=10; var b=20; console.log(a+b) })() console.log(a)//An error is reported. You can only access a inside the function
It is used to implement encapsulation for some third-party libraries, but because ES6 already has a modular syntax, immediate execution functions are not commonly used now.
Scope chain
Each function creates a new scope; The value inside the function cannot be accessed outside the function; Values outside the function can be accessed inside the function.
closure
Closure function: a function declared in a function is called a closure function.
Closure: an internal function can always access the declared parameters and variables in its external function, even after its external function is returned. (internal functions are returned and external functions are not destroyed)
In the following figure, fun2 is the closure function
function fun1(){ let str="hello"; let num=10; function fun2(){ let num=20; consolr.log(str); console.log(num) } fun2() }
We can get the value of n+m externally, but we can't get the values of n and M directly. Therefore, closures realize the encapsulation of code.
Closure example code: if the internal function is not completed, even if the external function is completed, the variables in the external function will not be destroyed.
function fun1(){ let n=10; let m=20; function fun2(){ return n+m; } return fun2; } const f=fun1(); const res=f(); console.log(res);
Arrow function
const fun=function(x){ return x*x; } Rewrite as const fun=(x)=>{ return x*x; } //If there is only one parameter, it can be further abbreviated as const fun=x=>{ return x*x; } //If the return value is an expression, it can be further abbreviated const fun=x=>x*x;
//Cat sayName every 1 second //The code is not output because this points to the window object and setInterval is the window function const cat= { name:"miaomiao", sayName(){ setInterval(function(){ console.log(this.name) },1000) } }
Change to
const cat= { name:"miaomiao", sayName(){ let self=this; setInterval(function(){ console.log(self.name) },1000) } }
Simplify with arrow function
const cat= { name:"miaomiao", sayName(){ setInterval(()=>{ console.log(this.name) },1000) } }
The arrow function and the ordinary function point to this differently
Ordinary functions point to the object that calls the function. Where the arrow function is defined, this points to who.
Regular expression basis
Regular expressions can be used to match strings. Through regular expressions, you can intercept strings or replace and verify the contents of strings according to rules. For example, verify the mailbox format, intercept the number part in "2021-7-25" and remove all letters in "121a3aa21aa2a".
To create a regular expression object:
var reg=new RegExp("123");
Abbreviation:
var reg=/123/;
case1
//test function var str="123";//str is usually user input var reg=/123/;//reg is generally a regular expression built into the system var res=reg.test(str); console.log(res); //res output is true
case2 specifies that the user can only enter letters
var reg=/[a-z]/;//[] represents the range. This expression filters individual letters and matches only one digit var str="abc"; var res=reg.test(str); console.log(res); //res output is still true res=reg.exec(str);//You can view the matching content. If the matching fails, null will be returned //The correct way to match only one bit is: reg=/^[a-z]$/;//^Start with $and end with $
Common syntax for regular expressions:
^: start $: ending []: Range {}: digit (): grouping +: Match 1 or more bits, the same as{1,} ?: 0 Bit or 1 bit, the same as{0,1} .: Match all, not an empty string \: Escape \d: number,Namely[0-9] \w: Numbers, letters, underscores \s: Spaces or line breaks
case3 matches two digits
var str="ab"; var reg=/^[a-z]{2}$/; var res=reg.test(str); console.log(res); //res output is true //Match 2-8 letters reg=/^[a-z]{2,8}$/; //Matches 2-8-digit letters or numbers or underscores reg=/^[a-z0-9A-Z_]{2,8}$/;//No spaces or other symbols are added in the middle //Abbreviation reg=/^\w{2,8}$/
case4 users can enter several digits
var reg=/^[0-9]{1,}$/ //Abbreviation var reg=/^\d+$/
case5 matching mailbox
var reg=/^\w{5,8}@\.com$/;//Yes To escape
case6 remove letters from string
var str="123abc456def"; var reg=/[a-zA-Z]/g;//g represents global matching, and the beginning and end are not written here var res=str.replace(reg,"")
case7 intercepting string
var str="2021-07-25"; var reg=/^(\d{4})-(\d{2})-(\d{2})$/; var res=reg.exec(str); console.log(res[0]);//2021-07-25 console.log(res[1]);//2021 console.log(res[2]);//07 console.log(res[3]);//25
ES2015 basic grammar
let and var
1. Use let instead of var
2. let does not work outside the block level scope
3. let does not allow variable promotion (cannot be used before declaration)
4. let does not allow duplicate declarations
const
1. It cannot be modified after definition
2. Invariant values are suitable for const declarations
3. The properties of a constant object can be changed
Template string
1. Use backquotes
//report errors let str="hello world";
//feasible let str=`hello world`
2. Support embedded variables
let year=2021; let month=7; let date=25; let res=`${year}year ${month}month ${date}day`
Destructuring assignment
Deconstruction assignment of array
let n=10; let m=20; become let [n,m]=[10,20]; //Realize exchange [n,m]=[m,n]
Structure assignment of object
let name="xiaoming"; let age=10; //become let {name,age}={name:"xiaoming".age:10};
Pass parameters through deconstruction assignment
let xiaoming={name:"xiaoming".age:10}; function getName(obj) { return obj.name; } //become function getName({name}){ return name; } let res=getName(xiaoming) console.log(res)
JS object oriented
ES5 object oriented knowledge
Constructor
ES5 has no concept of class and can only simulate classes through constructors.
The function name of the constructor, capitalized.
Constructors are used to create objects.
function Dog(name,age){ this.name=name; this.age=age; } var dog=new Dog("Wangwang",2);//Examples of dogs console.log(dog);
Prototype object prototype (prototype is an attribute of the constructor). Through the prototype object, we give new methods to the object generated by the constructor.
Dog.prototype.sayName=function(){ console.log(`My name is ${this.name}`); } var dog=new Dog("Wangwang",2); dog.sayName();
Use the prototype chain to realize inheritance (it is not a good inheritance implementation method, just understand it)
function Animal(name){ this.name=name; } Animal.prototype.sayName=function(){ console.log(`Hello, I'm ${this.name}`) } function Dog(name){ this.name=name; } Dog.prototype=new Animal(); var dog=new Dog(); dog.sayName();
ES6 object oriented knowledge
ES6 supports the concept of classes.
class Dog{ //Constructor constructor(name,age){ this.name=name; this.age=age; } sayName=function(){ console.log(`My name is ${this.name}`); } } let dog=new Dog("Wangcai",2); dog.sayName();
Implementation of inheritance
class Animal{ constructor(name){ this.name=name; } sayName(){ console.log('I'm an animal') } } class Dog extends Animal{ constructor(name,age){ super(name); this.age=age; } sayName(){ console.log('I'm a dog') } }
DOM Foundation
DOM is a set of standard programming interfaces. We operate html elements through the DOM interface.
Node type
- The entire document is a document node
- Each HTML element is an element node
- The text within an HTML element is a text node
- Each HTML attribute is an attribute node
- Annotations are annotation nodes
DOM: manipulate nodes and modify element styles.
DOM provides developers with a large number of APIs to operate the DOM tree through the document object.
Several methods
document.getElementById();//The return value is a dom node document.getElementByClassName();//The return value is a collection of dom nodes document.querySelector(); document.querySelectorAll(); domObject.innerHTML Gets and sets all content within the element
Example 1: operating a dom node
<h1 id="title">hello world</h1>
let h1=document.getElementById("title"); console.log(h1.innerHTML);//The output is hello world
Example 2 operates on a collection of dom nodes
<button class="btn">1</button> <button class="btn">2</button> <button class="btn">3</button>
let btns=document.getElementByClassName("btn"); for(let i in btns){ btns[i].innerHTML="text"; }
The first two functions are a little old. It is recommended to replace them with the following two.
Get a single node:
let h1=document.querySelector("#title");
Get node collection:
let btns=document.querySelectorAll(".btn");
Event type
Event listener function: when... Occurs, do... Things
1. Mouse event
Click: click event onclick
mouseenter: mouse entry event onmousenter
mouseleave: the mouse leaves the event onmouselive
2. Keyboard events
document.onkeydown=function(e){ let code=e.keyCode; }
Box attribute offset:
offsetTop/offsetLeft
3. Touch screen events
ontouchstart
ontouchend
ontouchmove
Modify style:
element.style.xxx
<div class="box"></div>
.box { width:100px; height:100px; background-color:red; }
let box=document.querySelector(".box") box.onmouseenter=function(){ this.style.backgroundColor:blue;//js use hump naming }
Set properties:
element.src
element.id
element.className (set the style before and after clicking)
...
innerHTML can not only read content, but also add tags.
such as
ul.innerHTML=` <li>Banana</li> <li>Pear</li> <li>Apple</li> `
Node operation
Create element node: createElement
Create text node: createTextNode
Add node: appendChild
Delete node: removeChild
<button> Button </button> <ul></ul>
let ul=document.querySelector('ul'); let btn=document.querySelector('button'); btn.onclick-function(){ let li=document.createElement("li"); let txt=document.createTextNode("Banana"); li.appendChild(txt); ul.oppendChild(li); }
event
Event object
The formal parameter event of the event listener function can obtain the event object.
The mouse coordinates can be obtained through the event object.
1. Obtain x coordinate: e.clientX
2. Obtain y coordinate: e.clientY
<div class="box"></div>
.box { width:100px; height:100px; background-color:red; }
let box=document.querySelector(.box); box.onclick=function(event){ console.log(event) } //event is a formal parameter. You can write anything, usually e
Event binding
1.addEventListener("eventType",function)
2.element.onEventType=function
difference:
1.addEventListener adds multiple events to the same event type on the same element, which will not be overwritten, but onEventType will be overwritten.
2.addEventListener can set the element to trigger events in the capture phase, but onEventType cannot (it can only be triggered when the event bubbles).
btn.onclick=function(){ console.log("hello world") } btn.onclick=function(){ console.log("hello js") } //Finally, only hello js is output
btn.addEventListener("click",function(){ console.log("hello world") }) btn.addEventListener("click",function(){ console.log("hello js") }) //Both outputs
Event flow
If three div s are nested, they are bound to the click event. Click the innermost element. How will the event be executed?
<div class="big"> <div class="medium"> <div class="small"> </div> </div> </div>
Click the innermost layer to flow from inside to outside (event bubble)
Click the outermost layer to flow from outside to inside (event capture)
The event capture phase does not trigger events, and the event bubble phase will trigger events.
addEventListener can set the event trigger phase:
addEventListener(eventType,fun,boolean); //The third parameter is false by default, indicating that the bubbling phase is triggered; If true, it is triggered in the capture phase
Prevent event bubbling:
e.stopPropagation();
Remove event default behavior:
e.preventDefault() / return false
For example, the jump behavior of removing the a tag.
Event delegation
Delegate the events of child elements to the parent through e.target.
e.target refers to the lowest element of event capture.
Timer method
1.setInterval and clearInterval
<button>suspend</button>
let timer=setInterval(()=>{ console.log("hello world") },1000); let btn=document.querySelector("button"); btn.onclick=function(){ clearInterval(timer); }
Tip: in order to prevent multiple timers, you can clear the original timer before each execution
2.setTimeout and clearTimeout
Anti shake and throttling
In solving performance problems, it is often encountered in development.
debounce: when the event is triggered multiple times in a short time, you can use the anti shake stop event to trigger continuously.
Throttling: prevent the event from being triggered many times in a short time, but it still needs to be triggered continuously in the interval.
window.onscroll event
//Anti shake let timer=null; window.onscroll=function(){ if(timer!=null){ clearTimeout(timer); } timer=setTimeout(()=>{ console.log("hello world") timer=null; }) }
//throttle let mark=true; window.onscroll=function(){ if(mark){ setTimeout(()=>{ console.log("hello world") mark=true; },500) } mark=false; }
//Encapsulating anti shake function with closure function debounce(fun){ let timer=null; function eventFun(){ if(timer!=null){ clearTimeout(timer); } timer=setTimeout(()=>{ fun(); timer=null; },500) } return eventFun; } window.onscroll=debounce(()=>{ console.log("hello world") });
BOM basis
Javascript=ECMAScript+DOM+BOM
DOM: Document Object Model (document object)
BOM: Browser Object Models
BOM object
window object (global object)
All methods that can be used directly in the browser are window object methods.
Such as timer method and pop-up box method
The screen object contains information about the user screen
The location object is used to get the address (URL) of the current page and redirect the browser to a new page
1.loacation.href-"https://www.baidu.com"
2.location.hostname - host domain name - "www.baidu.com"
3.location.pathname - current page path and file name - "/ s"
4.location.port port - "8080"
5.location.protocol protocol - "https:"
The history object contains the history of the browser
The navigator object contains information about the visitor's browser
Original and reference types
difference
1, Difference of assignment
The original type is assigned a value, and the reference type is assigned a reference.
Example code:
Original type
let str1="hello" let str2=str1; str1="world" console.log(str1);//world console.log(str2);//hello
reference type
let obj1={name:"Xiao Ming"} let obj2=obj1; obj1.name="Xiao Hong"; console.log(obj1.name);//Xiao Hong console.log(obj2.name);//Xiao Hong
2, Comparative differences
The original type compares values, and the reference type compares whether a reference points to the same object.
3, Difference of transmission parameters
The original type is used as a parameter, and the operation in the function does not affect the value of the actual parameter; The reference type is used as the parameter, and the operation in the function will affect the value of the argument.
Example code:
Original type
function fun(x){ x=100; console.log(`x The value of is ${x}`) } let num=10; fun(num); console.log(`num The value of is ${num}`) //The value of x is 100 and the value of num is 10
reference type
function fun(o) { o.name="Xiao Hong"; console.log(`o Your name is ${o.name}`) } let obj={name:"Xiao Ming"}; fun(obj); console.log(`obj Your name is ${obj.name}`) //o's name is Xiaohong and obj's name is Xiaohong
Type detection
Original data type detection: typeof(val)
value | type |
---|---|
100 | number |
"hello world" | string |
Not defined | undefined |
true | boolean |
null | object |
Reference data type detection: val instanceof type
All reference types are output as objects with typeof. (such as arrays, regular expressions, Date objects, etc.)
let arr=[1,2,3]; console.log(arr instanceof Array);//Output true
Synchronous and asynchronous Fundamentals
Synchronization: when you make a call, you can only call one person first and then the next one
Asynchronous: send text messages. You can send text messages to one and another
let target="hello world"; function getData(){ setTimeout(()=>{ return target },500) } let result=getData() console.log(result) //Show undefined
Solution
1. Callback function: pass a function as a parameter to another function
function getData(fun){ setTimeout(()=>{ fun(target) },500) } getData((d)=>{ console.log(d); })
2. Obtain data with promise object
promise object is a built-in object provided by ES6 to handle asynchronous problems.
let target="hello world" let p=new Promise((resolve)=>{ setTimeout(()=>{ resolve(target) },500) }) p.then((d)={ console.log(d) })
Using promise object to solve the problem of getData
function getData(){ return new Promise((resolve)=>{ setTimeout(()=>{ resolve(target) },500) }) } let p=getData() p.then((d)=>{ console.log(d) })
3. Use async function to solve asynchronous problem
let target="hello world"; function getData(){ return new Promise((resolve)=>{ setTimeout(()=>{ resolve(target) },500) }) } async function fun(){ let data=await getData() console.log(data) } fun()