当前位置:网站首页>I have summarized the knowledge points of JS [intermediate and advanced] for you
I have summarized the knowledge points of JS [intermediate and advanced] for you
2022-06-13 09:18:00 【Where is the beautiful dust heap】
List of articles - Write it at the front
- Constructors
- new What did you do when you were ?
- Instance members and static members
- Problems with constructors
- Prototype of instance object , **__proto__**
- Method lookup rule
- constructor Function one Pass parameters and self execution ( Class )
- constructor Function two , Point the referenced constructor back to the original Example c-6
- Constructor's “ Inherit ”
- summary
- Prototypes and prototype chains
- Classes and objects
- Closures and problems with closures
- this Direction problem of
- Object.defineProperty
- Shallow copy and deep copy
- js The higher-order function of
- recursive
- ES6 New characteristics
- The remaining parameters
- Extension operator
- Array.from
- Array.find
- Array.every
- Array.some
- Array.findIndex
- Array.includes
- startsWith() and endWith()
- repeat
- set
- utilize set Remove the duplicate of the array
- Traverse set
- difference let const var
- let
- const
- var
- Deconstruct assignment operation
- Arrow function
- Template string
- Wrote last
- Constructors
- new What did you do when you were ?
- Instance members and static members
- Problems with constructors
- Prototype of instance object , **__proto__**
- Method lookup rule
- constructor Function one Pass parameters and self execution ( Class )
- constructor Function two , Point the referenced constructor back to the original Example c-6
- Constructor's “ Inherit ”
- summary
- Prototypes and prototype chains
- Classes and objects
- Closures and problems with closures
- this Direction problem of
- Object.defineProperty
- Shallow copy and deep copy
- js The higher-order function of
- recursive
- ES6 New characteristics
- The remaining parameters
- Extension operator
- Array.from
- Array.find
- Array.every
- Array.some
- Array.findIndex
- Array.includes
- startsWith() and endWith()
- repeat
- set
- utilize set Remove the duplicate of the array
- Traverse set
- difference let const var
- let
- const
- var
- Deconstruct assignment operation
- Arrow function
- Template string
- Wrote last
Write it at the front
This article sums up js There are some fallible and confusing conceptual problems in the medium and high level , It mainly includes the following module
- Constructors
- Prototypes and prototype chains
- class
- Closures and problems with closures
- this Direction problem of
- Object.defineProperty
- Shallow copy and deep copy
- js The higher-order function of
- recursive
- ES6 in let const var
- ES6 Deconstruction assignment operation in
- ES6 Arrow function
- ES6 Template string
I will try my best to explain every point of knowledge , Write some Demo Here you are , Just like the previous one canvas It's the same when , Write as much descriptive code as possible , Two purposes , The first is to summarize , The second is to make a record , Also to learn js Some confused tips in the process of , This article belongs to js Medium to high , So the beginner seems to have some difficulties , But the primary can directly Baidu or see some of my previous about js It is also possible to learn from the articles of ! Although each of the above points can be directly taken out to write an article , It's not that I didn't have such a plan , It's just that I think this knowledge point will be obvious. It seems very difficult , Will dissuade some people , So just write an article and get it done , It will be a long time , And the previous applet and canvas equally , Because recently, I have written some summary articles , May be relatively cumbersome , When you read it, you can collect it directly , Take your time in the back ! I will try my best to divide each module clearly !
Constructors
Conceptual explanation : Constructor is also a kind of js function , But he is special , First, it has a special function , It mainly initializes some kind of object ( A certain category ), Encapsulate some common attributes of member variables into functions , The second special is that it is always associated with new Use it together , That is, if it doesn't go on and new In combination with , Then this constructor is meaningless , In general, we want to distinguish between ordinary functions and constructors , When declaring a constructor, the first letter is capitalized ! In object-oriented programming languages, there is basically the concept of class , however js There is no concept of class in itself , however js It's also object-oriented programming , His alternative is the constructor , The function of constructor is actually a disguised class , It has basically all the characteristics of a class , Let's declare the simplest constructor Example c-1
// Declare the simplest constructor , Animal species c-1
function Ani(aName,aGender){
this.aName = aName
this.aGender = aGender
this.eatFood = function(){
console.log(` Animals eat `)
}
}
let animal = new Ani(' Dog ',' Male ')
animal.eatFood()
console.log(animal)
// Animals eat
//Ani { aName: ' Dog ', aGender: ' Male ', eatFood: [Function] }
new What did you do when you were ?
- An empty object is initialized in memory
- take this Point to this empty object
- Execute the code in the constructor , Assign the contents of the constructor to an empty object
- Return the instance object itself
Instance members and static members
- As the name suggests, an instance member refers to a member that can be directly called by an instance object ( Or it can be understood as this Members pointed to ), Like the one above aName、aGender、earFood(), These members can only be called through the instance object , The constructor itself is not accessible 【Ani.aName】 It's wrong.
animal.eatFood()
animal.aName
animal.aGender
- Static members are members that are added directly through the constructor itself
Ani.age = 12 //age Is a static member , Add directly through the constructor , At the same time, it can only be accessed through the constructor , Instance objects are not accessible
console.log(Ani.age)
Problems with constructors
- Memory waste and solutions
If there is no reference data type in the constructor and all data types are basic data types , There is no memory waste , Let's be simple , Because the reference data type is used , The system will add a new piece of memory space , To solve this problem , Generally, it is recommended to write the reference data type or public method directly to the constructor prototype for shared memory address . The functions allocated through the prototype are shared by all members , The so-called prototype prototype, Every constructor has , If you don't understand here , You can think of them as a family , If there is a constructor, there must be prototype,prototype Itself is an object , Its properties and methods are owned by constructors Example c-2
// c-2
function Ani(aName,aGender){
this.aName = aName
this.aGender = aGender
this.eatFood = function(...foodType){
console.log(` eat ${foodType}`)
}
}
let dog = new Ani()
let cat = new Ani()
dog.eatFood(' The bone ',' meat ') // Eat bones
cat.eatFood(' Dried fish ') // Eat dried fish
// The eating function here is actually called by any animal , They all do one thing , Just eat , But when two different instance objects are called , Memory is declared twice , This causes a waste of memory , Write this function to the prototype , Share memory addresses , That is, no more memory space will be opened up
Ani.prototype.eatOther = function(...FT){
console.log(` eat ${FT}`)
}
dog.eatOther(' The bone ',' meat ') // Eat bones
cat.eatOther(' Dried fish ') // Eat dried fish
// prove : Check whether the two function addresses are the same
console.log(dog.eatFood === cat.eatFood) //false
console.log(dog.eatOther === cat.eatOther) //true
Prototype of instance object , proto
Through the example above , We can see ,dog and cat Can be accessed directly eatOther Methods , But our eatOther The method of is clearly assigned directly by the prototype object , Not an attribute inside the constructor , Why can our instance objects be accessed ? There are two explanations , But it's all right , The first is that both the attribute and method constructors assigned by the prototype object have , The second explanation is actually an extension of the first , Why do you have it ? because Each instance object has a proto The existence of archetypes , This proto It's pointing to prototype 了 , So the instance object can directly access the properties and methods on the prototype object , Example c-3
// c-3 __proto__ demonstration
function Ani(aName, aGender) {
this.aName = aName
this.aGender = aGender
}
Ani.prototype.eatOther = function (...FT) {
console.log(` eat ${FT}`)
}
let dog = new Ani(' Dog ', ' Male ')
// prove : Of instance objects __proto__ Yes Prototype object as follows :
console.log(dog.__proto__ === Ani.prototype) //true
console.dir(dog)
/**
aGender: " Male "
aName: " Dog "
[[Prototype]]: Object
eatOther: ƒ (...FT)
constructor: ƒ Ani(aName, aGender)
[[Prototype]]: Object
constructor: ƒ Object()
hasOwnProperty: ƒ hasOwnProperty()
isPrototypeOf: ƒ isPrototypeOf()
propertyIsEnumerable: ƒ propertyIsEnumerable()
toLocaleString: ƒ toLocaleString()
toString: ƒ toString()
valueOf: ƒ valueOf()
__defineGetter__: ƒ __defineGetter__()
__defineSetter__: ƒ __defineSetter__()
__lookupGetter__: ƒ __lookupGetter__()
__lookupSetter__: ƒ __lookupSetter__()
__proto__: Object
eatOther: ƒ (...FT)
constructor: ƒ Ani(aName, aGender)
[[Prototype]]: Object
get __proto__: ƒ __proto__()
set __proto__: ƒ __proto__()
*/
Method lookup rule
- Look in the instance object itself
- The instance object itself does not exist , Just find the instance object prototype __proto__ Whether the constructor prototype object on exists example c-4
// Method lookup rule Demo c-4s
function Ani(aName, aGender) {
this.aName = aName
this.aGender = aGender
}
Ani.prototype.eatOther = function (...FT) {
console.log(` eat ${FT}`)
}
let dog = new Ani()
// If dog It has its own method , You won't find the method on the prototype object
dog.eatOther = function (...FT) {
console.log(` Don't eat ${FT}`)
}
dog.eatOther(' Dried fish ')
// Don't eat dried fish
constructor Function one Pass parameters and self execution ( Class )
Instance object prototype __proto__ And prototype objects prototype There is an attribute in it , be called constructor, It's also called a constructor , Because it points to the constructor itself , If you pay attention , Example c-3 There is... In the printed information of constructor Appearance , His ** The purpose is to indicate which constructor is referenced by the current ** Example c-5
// prove :contructor It points to the constructor itself c-5
function Ani(aName, aGender) {
this.aName = aName
this.aGender = aGender
}
let dog = new Ani()
console.log(Ani === Ani.prototype.constructor) //true
console.log(Ani === dog.__proto__.constructor) //true
constructor Function two , Point the referenced constructor back to the original Example c-6
//c-6
// Basic writing
function Ani(aName, aGender) {
this.aName = aName
this.aGender = aGender
}
Ani.prototype.eat = function () {
console.log(" eat ")
}
Ani.prototype.move = function () {
console.log(" Move ")
}
let dog = new Ani()
console.log(Ani.prototype.constructor)
// Print information : It can be seen that , Current constructor It's pointing Ani Of this constructor
// Ani(aName, aGender) {
// this.aName = aName
// this.aGender = aGender
// }
// Change the way you write it
Ani.prototype = {
eat:function(){
console.log(" eat ")
},
move:function(){
console.log(" Move ")
}
}
console.log(Ani.prototype.constructor)
// Print information : You can see , Current constructor It's not pointing to Ani 了
//Object() { [native code] }
// Redirect the reference constructor to Ani
Ani.prototype = {
// Redirect the reference constructor to Ani, Need to put Ani Re feed to constructor
constructor:Ani,
eat:function(){
console.log(" eat ")
},
move:function(){
console.log(" Move ")
}
}
console.log(Ani.prototype.constructor)
// Print information
// Ani(aName, aGender) {
// this.aName = aName
// this.aGender = aGender
// }
Constructor's “ Inherit ”
Why do I put double quotation marks here ? Because the constructor itself has no inheritance , At least es6 It wasn't before , however js Some features of inheritance are implemented by adding the constructor to the prototype object , So it can also be called inheritance in a certain sense , First of all, understand what inheritance is , You can jump directly to the class inheritance introduction , Class inheritance has extends keyword , But constructors don't , however js Provides call The method can be this Change of direction of ,【this The change of direction of can be moved to the following this Direction problem of 】, Then we can go through call Change the point of the child constructor to that of the parent constructor this, Then the pseudo inheritance is realized Example :c-c
//c-cs
function F(x, y) {
this.x = x
this.y = y
}
function C(x, y) {
// take this Point to the parent constructor
F.call(this, x, y)
}
let c = new C(1, 2)
console.log(c) //C { x: 1, y: 2 }
- Method inheritance
function F(x, y) {
this.x = x
this.y = y
}
F.prototype.move = function(){
console.log(" I will go ")
}
function C(x, y) {
F.call(this, x, y)
}
// You can't just C.prototype = F.prototype This will cause a method to be added to the parent constructor when adding a method to the child constructor
C.prototype = new F()
let c = new C(1, 2)
c.move() // I will go
summary
Maybe the first knowledge point persuaded some people to retreat , I admit that what I wrote was boring , But learning this thing itself is very boring , Here's a summary of constructors , example , The relationship among prototype objects , First, the constructor has a prototype The properties of point to the prototype object , There is one on the prototype object constructor Points to the constructor , The prototype of the instance __proto__ Point to the prototype object , And because the prototype object points to the constructor , therefore __proto__ It also points to the constructor , It's a little twisted , But I understand , It's easier ! So much for constructors !
Prototypes and prototype chains
Prototype chain
Prototype chain is a difficult thing to understand , But as long as the constructor above is clear , This prototype chain should not be a problem , Let's briefly talk about the prototype chain , This is a difficult knowledge point for many people , Example c-7 Of instance objects proto The prototype of refers to the prototype object prototype, Prototype object prototype Of proto The archetype points to Object Of prototype,Object.prototype.proto The archetype points to null, Such a prototype point is called the prototype chain
//c-7 Prototype chain demonstration
function Ani(aName, aGender) {
this.aName = aName
this.aGender = aGender
}
let dog = new Ani()
// On the prototype object __proto__ Yes Object Prototype object ,
console.log(dog.__proto__.__proto__)
console.log(Ani.prototype.__proto__)
console.log(Object.prototype)
console.log(Object.prototype.__proto__)
// Of instance objects __proto__ The prototype of refers to the prototype object prototype, Prototype object prototype Of __proto__ The archetype points to Object Of prototype,Object.prototype.__proto__ Prototypes point to null, What such a prototype points to is called the prototype chain
console.log(dog.__proto__.__proto__ === Ani.prototype.__proto__) //true
console.log(Ani.prototype.__proto__ === Object.prototype) //true
Member lookup mechanism
The above shows what the prototype chain is through a piece of code , What is his role ? One of the main functions of prototype chain is to find attribute methods , When accessing the properties of an instance object , It is searched in the following order
- First, check whether the instance object itself has this attribute
- Next, look for his prototype __proto__ Is this attribute available 【 In fact, whether the prototype object has this attribute , because __proto__ It points to the prototype object 】
- Then find out whether the prototype of the prototype object has , That is to say Object There is no such thing as
- Finally, I found null until
Example c-8
// c-8
function Ani(aName, aGender) {
this.aName = aName
this.aGender = aGender
}
let dog = new Ani()
dog.name = ' Dog '
console.log(dog.name) // Dog
Ani.prototype.pName = ' puppy '
console.log(dog.pName) // puppy
Object.prototype.oName = ' Golden hair '
console.log(dog.oName)// Golden hair
console.log(dog.nName) //undefined
Classes and objects
Before we talk about classes , Let's start with two programming ideas , One is process oriented , One is object-oriented , This estimate has been said by many people and can not be said any more , No matter which computer language appears , Will first explain whether it is process oriented or object-oriented , There is no obvious difference between the two , Just two different ways to solve the problem , Process oriented problem solving steps , for instance , Facing the process is like eating an egg fried rice , Object oriented is like eating a portion of cappuccino , The difference is that fried rice with eggs is delicious , But you want to put eggs in fried rice without eggs , It's more troublesome , The advantages of capping pouring surface are , The first two sides are separated , You can have whatever you like , I wonder if such an example will help you better understand these two different ideas , Let's talk about the class , It is an object-oriented idea , That is to encapsulate different functional modules , Finally, different functions are realized through different combinations ! The advantage of object orientation is flexibility , The advantage of process orientation is that it has good performance , Class, too es6 Then bring it up , But because there is so much to say , So I'll talk about it alone ! Class itself is also a constructor object : stay js Everything is an object , Such as method , Variable , Methods, etc. The relationship between classes and objects : Class is a large class , Like animals , An object is a typical concrete of a class , Like dogs , Cat, etc Example c-9
Object oriented features
- encapsulation
- inheritance
- polymorphism
Create classes and instance objects
//c-9
// Create an animal class
class Ani {}
// Create an instance object
let d = new Ani()
constructor
The constructor section has already talked about constructor, In class ,constructor Also called a constructor , Its role is to pass parameters and return instance objects , adopt new It's automatically executed when it's done constructor Code in , If we don't write constructor Words , Class will automatically help us create a constructor Example c-10
//c-10
class Ani {
constructor(aName, aGender) {
this.aName = aName
this.aGender = aGender
this.eatFood()
}
eatFood(){
console.log(' I am here new The time was executed ')
}
}
new Ani() // I am here new The time was executed
Class inheritance
Classes and classes Can be inherited , After the child class inherits the parent class , It inherits all its properties and methods , in other words , The methods and properties of the parent class can be reused by the child class Example c-11
//c-11
class Ani {
constructor(aName, aGender) {
this.aName = aName
this.aGender = aGender
}
eatFood() {
console.log(' I inherited it ')
}
}
class Dog extends Ani {}
let d = new Dog(' Golden hair ')
console.log(d.aName) // Golden hair
d.eatFood() // I inherited it
super keyword
So let's talk about that super Use , After the child class inherits the parent class , Because each class has its own constructor Constructors , They also have their own formal parameters , So when the parent class uses its own parameters for processing operations , If the subclass directly calls the method of the parent class, an error will be reported , That is to say this Direction problem of , Example :c-12
//c-12
class F {
constructor(m, n) {
this.m = m
this.n = n
}
productNum() {
console.log(this.m * this.n)
}
}
class C extends F {
constructor(x, y) {
this.x = x
this.y = y
}
}
let c = new C(1, 2)
c.productNum()
// Report errors :Must call super constructor in derived class before accessing 'this' or returning from derived constructor
The problem arises when we pass parameters ,constructor Itself is the constructor of the current class , So we have no way to call the parent class directly productNum Methodical , At this time, we need to tell the current subclass , The arguments we pass are for the parent class , Not what you want to use Example :c-13
- super Call the constructor of the parent class
// c-13
class F {
constructor(m, n) {
this.m = m
this.n = n
}
productNum() {
console.log(this.m * this.n)
}
}
class C extends F {
constructor(x, y) {
// Call the constructor of the parent class
super(x, y)
}
}
let c = new C(1, 2)
c.productNum() // 2
- super Call the normal function of the parent class In the use of super We usually use it to call the constructor of the parent class , That is, change the transfer direction of formal parameters , So in fact super You can also call the normal function of the parent class , For example 14
// c-14
class F {
ordinaryFunction() {
console.log(" I am a F class ")
}
}
class C extends F {
ordinaryFunction() {
console.log(" I am a C class ")
}
}
let c = new C()
c.ordinaryFunction() // I am a C class
// Method search order after class inheritance : The instance object lookup method first finds the instance object in itself , Cannot find the parent class
Call the normal function of the parent class Method search order after class inheritance : The instance object lookup method first finds the instance object in itself , Cannot find the parent class
// c-14
class F {
ordinaryFunction() {
console.log(" I am a F class ")
}
}
class C extends F {
ordinaryFunction() {
super.ordinaryFunction()
}
}
let c = new C()
c.ordinaryFunction() // I am a F class
- super After use , Also execute custom methods
After the subclass inherits the method of the parent class , Most of the time, we need custom functions to handle some business , At this time, we can put super Write it together with your own formal parameters For example c-15 It should be noted that super Must be written before its own variable assignment
// c-15
class F {
constructor(m, n) {
this.m = m
this.n = n
}
add() {
console.log(this.m + this.n)
}
}
class C extends F {
constructor(x, y) {
super(x, y)
this.x = x
this.y = y
}
minus() {
console.log(this.x - this.y)
}
}
let c = new C(1, 2)
c.add() //3
c.minus() //-1
- Points of attention :
- Class has no variable promotion , That is to say, a class must be defined first , Only then can we carry on the instance conversation
- The properties and methods in the class must use this Point to
- Class this Direction problem of constructor Inside this Points to the instance object Method this It's the caller . Example c-16
//c-16s
let that,_this
class F {
constructor(m, n) {
this.m = m
this.n = n
that = this
}
add() {
_this = this
}
}
let f = new F(1, 2)
console.log(f === that) //true
f.add()
console.log(f === _this) //true
summary
So far about this The question pointed to is finished , Because of the length and my personal ability , I don't want to write something specific this Pointed question , These are basically enough for our daily programming , About the above this Point to why there is no validation , Two reasons , The verification process requires screenshots , It's a long time in itself , The picture will be longer , The second is This kind of verification is more intuitive and easy to remember when you actually operate it , So I won't verify them one by one , But the above code is self verified , It's all right , If you have any questions, please write to me directly or leave a message below !
Closures and problems with closures
The first thing to understand before talking about closures is the concept of scope , stay js Variables inside functions in can only be called inside functions , External is not callable , Internal variables are also called local variables , After function execution , This variable will also be destroyed , I am here. js It is said in the garbage collection mechanism of , If you are interested, you can read , Closures break the conventional concept of scope , It allows one function to access variables inside another function , This phenomenon or function is called closure Example c-b
//c-b
function bb() {
let name = "jim"
return function() {
console.log(name)
}
}
bb()()
//jim
// perhaps
function bb() {
let name = "jim"
function nb() {
console.log(name)
}
nb()
}
bb()
//jim
- How to verify whether closures are generated stay google Browser console bb The breakpoint of the function , When you go to the next step , Execute to internal nb When , The function prompt of closure will appear on the right , Above bb Is a closure function or bb Function produces the phenomenon of closure
- How closures cause memory leaks
A question often asked during the interview is that closures may cause memory leaks , The first thing to understand about this problem is what is called a memory leak , stay js A memory leak in indicates the end of the program , The phenomenon that unused or used variables should be destroyed but not destroyed is called memory leak , So according to what I said before js The memory clearing mechanism knows ,js Is written by a root Node to find whether the variable is used to determine whether it needs to be destroyed , The execution of ordinary functions will not be terminated root Node found , So it will be destroyed , But closures are internal calls , therefore js When searching, the internal function is still calling this variable , At this time, he will not actively destroy this variable , This leads to a memory leak !
this Direction problem of
this All the problems are headache problems , Because there are many situations involved , In fact, I can't guarantee that I'm sure of all the situations , Most of the time I also write a demo Try it on your own , have a look this What is the direction of , So the following examples are some of the more meaningful ones in the process of writing , I hope it can help you understand the content of this section The general principle is this All points to the caller
How to define a function Example c-z
Without saying this Before pointing to the problem , The first thing to understand is , Functions are defined in many ways , Because different definitions mean this It's different , Here are some common definitions of functions
// Custom function c-z
function f(){}
// Function expression Anonymous functions
let f = function(){}
// new Function
let n = new Function()
// All functions are Funtion Instance object of
How to call function Example c-f
//c-f
function f(){}
f() // Function name execution this Pointing to window
let o = {f:function(){}}
o.f() // Object reference execution this Pointing to o
function F(){}
new F() // Execute when instantiating this It points to the instance object
element.onclick = function(){} // Element Click to execute this Pointing to element
setInterval(()=>{},1000) // In a second this Pointing to window
(()=>{})() // Execute now this Pointing to window
- this Point to the problem Describe the above call methods respectively
- When using ordinary functions this Point to the window
- When we use constructors this The execution is the instance object
- Object method call this Point to the object
- Event element binding this Points to the element
- Timer and immediate execution function this It points to window
- In the constructor this It points to the instance object example c-17
//c-17
let that
function F(){
that = this
}
let f = new F()
console.log(f === that) // true
- Methods in prototype objects this It's the caller , In fact, this is consistent with the class , You can see c-16 Example
let _this
function F() {}
F.prototype.move = function () {
_this = this
}
let f = new F()
f.move()
console.log(f === _this) //true
- Use call、apply、bind change this The direction of
call
call There are two functions First of all : You can call functions directly and execute second change this The direction of call You can also pass parameter examples c-t
//c-t
function f(x, y) {
console.log(x, y)
console.log(this)
}
f()
//Window {window: Window, self: Window, document: document, name: '', location: Location, …}
let o = {
name: 'jim'
}
f.call(o, 1, 3)
//1 3
// {name: 'jim'}
apply
call There are two functions First of all : You can call functions directly and execute second change this The direction of call You can also pass parameters and call The difference is that its arguments must be an array Example c-a
//c-a
function f(x, y) {
console.log(x, y)
console.log(this)
}
let o = {
name: 'jim'
}
f.apply(o, [1,2]) // Here and call The difference is that its parameters must be an array
//1 2
// {name: 'jim'}
Bind
bind It can also be changed this The direction of , But he doesn't immediately execute the function , But he will change this Point to the following function to return , His parameters are also string type Example c-b
//c-b
function f(x, y) {
console.log(x, y)
console.log(this)
}
let o = {
name: 'jim'
}
let newf = f.bind(o, 1, 2)
newf()
//1 2
// {name: 'jim'}
- For example
let btn = document.getElementById('btn')
btn.onclick = function () {
console.log(this) // Pointing to btn
setTimeout(function () {
console.log(this) // Pointing to btn( It originally pointed to window)
}.bind(btn), 3000)
}
Object.defineProperty
This thing if you can vue Words , It should not be too strange , because vue The two-way binding mechanism of is implemented through this attribute , This attribute is the method to define a new attribute or modify an existing attribute c-o
- General methods of modifying objects
//c-o
let o = {
name: "karry",
age: 18,
height: '180cm'
}
o.score = 100
o.age = 20
console.log(o) //{ name: 'karry', age: 20, height: '180cm', score: 100 }
- Use Object.defineProperty Make changes c-u
//c-u
let o = {
name: "karry",
age: 18,
height: '180cm'
}
Object.defineProperty(o,'age',{
value : 22,// The current value
writable : true, // Can it be rewritten Default false
enumerable : false, // Whether it can be traversed Default false So there is no value Value
configurable : true, // Whether it can be modified or deleted again Default false
})
console.log(o)
//{ name: 'karry', height: '180cm' }
There is no specific explanation here , Just try it yourself , There is nothing difficult to understand , The best way is to try every attribute
- Get set Example c-s
//c-s
let o = {
name: "karry",
age: 18,
height: '180cm'
}
let { name, age, height } = o
Object.defineProperty(o, 'age', {
set(nAge) {
console.log(` My name is ${name}, My age is ${nAge}`)
},
get() {
return 20
}
})
o.age = 19 // My name is karry, My age is 19
console.log(o.age) //20
- Add one for each attribute get set Method That is to say vue Inside data Function return Out of the monitored value c-v
//c-v
let o = {
name: "karry",
age: 18,
height: '180cm'
}
for (let i in o) {
Object.defineProperty(o, i, {
set(i) {
console.log(` My attribute is ${i}`)
},
get() {
console.log(this)
}
})
}
o.name = 'jim'
o.name
// My attribute is jim
//{
// name: [Getter/Setter],
// age: [Getter/Setter],
// height: [Getter/Setter]
//}
Shallow copy and deep copy
- Shallow copy
Shallow copy is a common method : Example c-c1
- Direct assignment
- for Traverse
// Direct assignment c-c1
let o = {
name: "jim",
age: 18,
child: {
name: 'kim'
}
}
let k = {}
k = o
//{ name: 'jim', age: 18, child: { name: 'kim' } }
//for Traverse
for (let i in o) {
k[i] = o[i]
}
console.log(k)
//{ name: 'jim', age: 18, child: { name: 'kim' } }
- Problems with shallow copy
Shallow copy is actually an address for copying the original object , The basic data type has no new address , There is a new address for the reference data type , In fact, if we copy an address , This means that changes to the copied object will result in changes to the original object Example :c-w
//c-w
let o = {
name: "jim",
age: 18,
child: {
name: 'kim'
}
}
let k = {}
for (let i in o) {
k[i] = o[i]
}
console.log(k) //{ name: 'jim', age: 18, child: { name: 'kim' } }
k.name = 'marry' // The basic data type will not change
k.child.name = 'karry' // Referencing the data type will cause the original object to change
console.log(o) //{ name: 'jim', age: 18, child: { name: 'karry' } }
- Deep copy
Deep copy will copy the value in the past , Will request a new piece of memory , Does not affect previous object data , The most common is the use of JSON Direct deep copy Example c-s2
- JSON.parse(JSON.stringify(o))
//c-s2
let o = {
name: "jim",
age: 18,
child: {
name: 'kim'
}
}
let k = {}
k = JSON.parse(JSON.stringify(o))
console.log(k) // { name: 'jim', age: 18, child: { name: 'kim' } }
k.child.name = 'karry'
console.log(o) // { name: 'jim', age: 18, child: { name: 'kim' } }
console.log(k) //{ name: 'jim', age: 18, child: { name: 'karry' } }
- Recursive deep copy Example c-d1
//c-d1
/**
*
* @param {*} n Newly copied objects
* @param {*} o Previous copy objects
*/
let deepC = function (n, o) {
for (let i in o) {
let currItem = o[i]
if (currItem instanceof Array) {
// If it's an array , Directly transfer the current i Item to clear , Then give the data of the current old object to the new value
n[i] = []
deepC(n[i], currItem)
} else if (currItem instanceof Object) {
n[i] = {}
deepC(n[i], currItem)
} else {
n[i] = currItem
}
}
}
deepC(k, o)
console.log(k)
// { name: 'jim', age: 18, child: { name: 'kim' }, arr: [ 1, 2, 3 ] }
Be careful : there Array Belong to Object Therefore, the judgment conditions here can not be written in reverse , Otherwise, the copy will be incomplete
js The higher-order function of
In fact, we often use higher-order functions , It's just that we don't know it is a higher-order function in the process of using it , Higher order functions can satisfy either of the two conditions , The first is His shape parameter is a function , The second is that its return value is a function Example c-g1 and c-g2s
- Parameter is a function
//c-g1
function gf(callback){
callback && callback()
}
let f = function(){
console.log("this is function")
}
gf(f())
//this is function
- The return value is a function
// c-g2
function gf(){
return function(){
console.log("this is function")
}()
}
gf()
//this is function
recursive
Recursion refers to the function itself calling its own procedure, which is called recursion , A function written in this way is called a recursive function
- Calculate the factorial
This is usually the case with recursion , Let's also write about , The so-called factorial is 1234567… Process product , Given an argument , Calculate the product within the parameters Example c-d
//c-d
let jc = function (n) {
if (n === 1) {
return 1
}
return n * jc(n - 1)
}
console.log(jc(10)) //3628800
- Calculation tree Structured data Example c-t
//c-t
let data = [
{
id: 1,
name: ' mobile phone ',
child: [
{
id: 1 - 1,
name: ' Apple ',
child: [
{
id: 1 - 1 - 1,
name: '4S'
}
]
}
]
},
{
id: 2,
name: ' The computer '
}
]
let recursion = function (ary, id) {
var rO = {}
for (let i of ary) {
if (i.id === id) {
rO = i
} else if (i.child && i.child.length > 0) {
rO = recursion(i.child, id)
}
}
return rO
}
console.log(recursion(data, 1 - 1 - 1)) //{ id: -1, name: '4S' }
ES6 New characteristics
The remaining parameters
When the number of arguments is greater than the number of shape parameters , We can use the writing method of the remaining parameters to define the function Example c-a1
//c-a1
let fn = (arg, ...args) => {
console.log(arg) //1
console.log(args) //[ 2, 3, 4, 5 ]
}
fn(1, 2, 3, 4, 5)
- Used in conjunction with the deconstruction function , When we don't know the specific number , Can be deconstructed directly Example c-a2
//c-a2
let r = [1, 2, 3, 4, 5]
let [...args] = r
console.log(args) //[ 1, 2, 3, 4, 5 ]
let or = [
{ id: 1, name: 'jim' },
{ id: 2, name: 'tom' }
]
let [name1,name2] = or
console.log(name1,name2) //{ id: 1, name: 'jim' } { id: 2, name: 'tom' }
let [...names] = or
console.log(names) //[ { id: 1, name: 'jim' }, { id: 2, name: 'tom' } ]
Extension operator
> The extension operator is to split an array into comma separated sequences Example c-a3
//c-a3
let r = [1, 2, 3, 4, 5]
console.log(...r) //1 2 3 4 5
let or = [
{ id: 1, name: 'jim' },
{ id: 2, name: 'tom' }
]
console.log(...or) //{ id: 1, name: 'jim' } { id: 2, name: 'tom' }
Array.from
Put the pseudo array ( Traversable objects ) Change to a true array Example c-a4
//c-a4
let r = {
'0': '1',
'1': '2',
'2': '3',
length : 3
}
let nr = Array.from(r)
console.log(nr)
Array.find
Find the first data that meets the criteria , Only the first one will be found No more searching Example c-a5
//c-a5
let fo = [
{
id: 1,
name: 'jim'
},
{
id: 2,
name: 'kim'
},
{
id: 3,
name: 'tom'
},
{
id: 4,
name: 'jim'
}
]
let ro = fo.find((item) => item.name === 'jim')
console.log(ro) //{ id: 1, name: 'jim' }
Array.every
Find out whether every item in the array conforms to Back to a boolean Example c-a6
//c-a6
let eo = fo.every((item)=> item.name === 'jim')
console.log(eo) //false
Array.some
Find whether there is an item in the array Back to a boolean. Example c-a7
//c-a7
let eo = fo.some((item)=> item.name === 'jim')
console.log(eo) //true
Array.findIndex
Find the index of the first qualified value in the array Example c-a8
//c-a8
let eo = fo.findIndex((item)=> item.name === 'jim')
console.log(eo) //0
Array.includes
Check whether the array contains an item Example c-a9
//c-a9
let no = [1,23,4,4]
let r = no.includes(4)
console.log(r) //true
startsWith() and endWith()
Whether the string uses ** Beginning or end Example c-10
//c-a10
let str = 'this is clearlove blog'
let s = str.startsWith('this')
console.log(s) //true
let e = str.endsWith('blog')
console.log(e) //true
repeat
Make several copies of the string Example c-a11
//c-a11
let str = 'clearlove blog'
let c = str.repeat(4)
console.log(c) //clearlove blogclearlove blogclearlove blogclearlove blog
set
set yes es6 A new data structure , It's like an array , It's just that he doesn't repeat everything Example c-a12
//c-a12
let s = new Set()
s.add(1)
s.add(2)
s.add(3)
s.add(1)
console.log(s.size) //3
s.delete(3)
console.log(s) // { 1, 2 }
s.clear()
console.log(s) //{}
utilize set Remove the duplicate of the array
let r = [111, 2, 3, 4, 3, 2, 3, 4, 5]
let res = new Set(r)
console.log(res) // { 111, 2, 3, 4, 5 }
let ks = [...res]
console.log(ks) //[ 111, 2, 3, 4, 5 ]
let as = Array.from(res)
console.log(as) //[ 111, 2, 3, 4, 5 ]
Traverse set
let s = new Set()
s.add(1)
s.add(2)
s.add(3)
s.add(1)
s.forEach(i => {
console.log(i)
})
// 1,2,3
difference let const var
let
- With block level scope
let The emergence of is to perfect js Its own language defects , It may not be appropriate for me to say so ,js stay let Before appearance , Only global scope and local scope ,java It's the same in China , however let After that, the block level scope appears , It means being {} Included scopes such as : c-l
// c-l
if (1) {
let a = 1
}
console.log(a) //a is not defined
if(1){
var a = 1
}
console.log(a) //1
- for In circulation let It also has a certain block level scope We're in a for After the cycle , The declared variables can also be in for End of loop to access , In fact, it is unreasonable , such as
for (var i = 0; i< 9; i++) { }
console.log(i) //9
Use let This problem will not occur if the writing is changed
for (let i = 0; i < 9; i++) { }
console.log(i) //i is not defined
- Let No variable promotion
console.log(a)
let a = 1 //Cannot access 'a' before initialization
- There is a temporary dead zone
// Block level scope neutralization {} The binding of , So the external ones can't be used
var a = 1
if (1) {
console.log(a) //Cannot access 'a' before initialization
a = 2
let a = 1
}
const
- Used to declare constants , No change is allowed
const PI = 3
PI = 4
console.log(PI) //Assignment to constant variable
- There is also a temporary dead zone
// Block level scope neutralization {} The binding of , So the external ones can't be used
var a = 1
if (1) {
console.log(a) //Cannot access 'a' before initialization
a = 2
const a = 1
}
- Const The initial value must be assigned
const a
console.log(a) //Missing initializer in const declaration
var
- There is variable promotion
- Function level scope
- Values are modifiable
var Because it took too long , So I won't do too much code demonstration here
Deconstruct assignment operation
- The deconstruction of arrays
// The quantity must be one-to-one , Otherwise, it would be undefined
let r = ['jim', 29, ' Beijing ']
let [name, age, address] = r
console.log(name) //jim
console.log(age) //29
console.log(address) // Beijing
console.log(other) //undefined
- Object deconstruction
let o = {
name : 'jim',
age : 20,
add : ' Henan '
}
let {name,age,add,other} = o
console.log(name) //jim
console.log(age) //20
console.log(add) // Henan
console.log(other) //undefined
- Change the variable name
// Object deconstruction can be renamed directly , But arrays cannot
let o = {
name: 'jim',
age: 20,
add: ' Henan '
}
let { name: aName, age: aAge, add: aAdd, other: aOther } = o
console.log(aName) //jim
console.log(aAge) //20
console.log(aAdd) // Henan
console.log(aOther) //undefined
Arrow function
Grammatical sugar of function , That is, a simple way to function , He doesn't have his own this, So his this It points to his context , Because no this, So there's no way to use appay、call And so on this The direction of Example c-j
//c-j
let n = {
name: 'kim'
}
let o = {
name: "jim",
fn: () => {
console.log(this) //window
},
fn1: function () {
console.log(this) //kim
}
}
o.fn.call(n)
o.fn1.call(n)
Template string
es6 The template string operation is provided in , Simplified our code writing Example c-m
//c-m
let name = "jim"
let age = 20
console.log(` My name is ${name}, My age is ${age}`) // My name is jim, My age is 20
- You can also execute functions
let sayH = (name)=>{
return ` My name is ${name}`
}
console.log(`${sayH(name)}`) // My name is jim
Wrote last
In fact, about js There are many more advanced parts , But considering the space and personal ability , Let's write so much first , It's been two nights , Each example is written by oneself , They are also verified , So when you look at it, you can use it directly with confidence , If you have any questions, please contact me directly below , About js Let's update these for the time being , I may want to update about TS Knowledge points of , Not very good at summarizing js Relevant , But you can leave a message below for some knowledge points you want to know , I saw the , It will be updated directly in this article , Thanks for reading , Thank you !
边栏推荐
- Neo4j Environment Building
- 20211108 is transpose multiply a a a positive definite matrix? What are the necessary and sufficient conditions for a to be a positive definite matrix?
- SQL ROW_ The number() function uses
- LeetCode 6097. 替换字符后匹配(字典)
- 202012 CCF test questions
- Class loading overview
- LeetCode 5259. 计算应缴税款总额
- 20211005 Hermite matrix and some properties
- Cisco, Huawei network equipment
- QObject::connect: Cannot queue arguments of type ‘QTextCursor‘ (Make sure ‘QTextCursor‘ is registere
猜你喜欢
图数据库Neo4j介绍
C language: five custom types
Detailed explanation of C language callback function
Use typescript to complete simple snake eating function
20220606 关于矩阵的Young不等式
攻防世界PWN play 条件竞争漏洞的利用
Top+jstack to analyze the causes of excessive CPU
202012 CCF test questions
Some websites of QT (software download, help documents, etc.)
Cisco, Huawei network equipment
随机推荐
20211108 det(AB)=det(A)det(B)
Subspace of 20211004 matrix
马斯克的「元宇宙」梦
Lecture par lots de tous les fichiers vocaux sous le dossier
SQL ROW_ The number() function uses
Neo4j - CQL使用
20211006 linear transformation
Cisco, Huawei network equipment
20211028 调节和跟踪
阿里高级专家剖析 | Protocol的标准设计
C/S模型与P2P模型
全新BMW i3的操控,能符合对3系之名产品的期待吗?
JUC原子引用与ABA问题
Message Oriented Middleware
Tutorial (5.0) 04 Fortint cloud services and scripts * fortiedr * Fortinet network security expert NSE 5
BGP Federation +community
20211108 能观能控,可稳可测
LeetCode 202. 快乐数
Simple implementation of database link pool
C language: deep understanding of pointers and arrays