JS advanced learning (scope, function advanced, destructuring assignment, prototype chain)


This week, I mainly learned about prototypes and prototype chains, prototype attribute issues, scope and scope chains, closures, object creation patterns, and inheritance patterns. The following are the study notes I took this week

1. Introduction to object-oriented programming

Two major programming ideas

pop process oriented

oop object-oriented

Object-oriented has the advantages of flexibility, code reusability, easy maintenance and development, and is more suitable for large-scale software projects where multiple people collaborate.

Object-oriented features:

  • Encapsulation

  • inheritance

  • polymorphism

2. Classes and objects in ES6

Object- oriented (abstract, concrete)

In JS, an object is an unordered collection of related properties and methods, and all things are objects, such as strings, arrays, values, functions, etc.

Objects are composed of properties and methods:

  • Attribute: the characteristics of things, represented by attributes in objects (common nouns)
  • Method: the behavior of a thing, represented by a method in an object (common verb)

Classes abstract the common parts of objects

To create a class, you must use new to instantiate the class before it can be used

There is a very important function constructor constructor in the class

//创建一个类
class Star{
    
    
    constructor(uname,age){
    
    
        this.uname=uname;
        this.age=age;
    }
      //在类中添加方法
    sing(song){
    
    
        // console.log("我会唱歌")
        console.log(this.uname+song)
    }
    //(1)在类里面的所有函数不需要写function
    //(2)多个函数方法之间不需要添加逗号分隔
}
//利用类创建对象,也称对类进行实例化
var zly=new Star("赵丽颖",31);
var zs=new Star("某爽",28);
console.log(zly);
console.log(zs);
// (1)通过class对象创建类,类名习惯性首字母大写
// (2)类里面有个constructor函数,可以接受传递过来的参数,同时返回实例对象
// (3)constructor函数只要new生成实例时,就会自动调用这个函数,如果我们不写这个函数,类也会自动生成这个函数
// (4)生成实例的new不能省略
// (5)最后注意语法规范,创建类 类名后面不要加小括号,生成实例 类名后面加小括号,构造函数不需要加function

3. Class inheritance

super can not only call the constructor in the parent class, but also call the normal function of the parent class

//Search principles for attributes or methods in inheritance: proximity principle

//1. During inheritance, if the instantiated subclass outputs a method, first check whether the subclass has this method. If so, execute the subclass first.

//2. During inheritance, if there is no such method in the subclass, check whether there is such a method in the parent class. If so, execute the method in the parent class.

class Father {
    constructor(x, y) {
        this.x = x;
        this.y = y;
    }
    sum() {
        console.log(this.x + this.y);
    }
}
class Son extends Father {
    constructor(x, y) {
        //super必须在子类this之前调用
        super(x, y)//调用父类中的构造函数
        this.x = x
        this.y = y     
    }
    sub(){
        console.log(this.x - this.y);
    }
}
var son = new Son(5,3);
son.sub();
son.sum();

Classes and Objects in ES6

three points of attention

  1. There is no variable promotion in ES6, so the class must be defined first before the class can instantiate the object.
  2. Common properties and methods in the class must be used with this
  3. The pointing problem of this in the class
  4. This in the constructor points to the created instance object, and this in the method points to the caller of this method.
 var that;
 var _that;
class Star{
    
    
    constructor(uname){
    
    
    that=this
    console.log(this)
        this.uname=uname;
        this.btn=document.querySelector("button");
        this.btn.onclick=this.sing;//不要加小括号,加上后就立马执行了
    }
    //在类中添加方法
    sing(){
    
    
        //这个sing方法里的this指向的是btn这个按钮,因为这个按钮调用了这个函数
        console.log(this)
        console.log(this.uname)
    }
    dance(){
    
    
        //这个dance里面的this 指向的是实例对象zly 因为zly调用了这个函数
        _that=this
        console.log(this)
    }
}
var zly=new Star("赵丽颖")
zly.dance();
console.log(that===zly);
console.log(_that===zly);

scope

local scope

  • function scope
  • Block scope (for loop, if, while)

Let and const declarations will generate block scope, but var will not generate block scope.

Variables between different code blocks cannot access each other

It is recommended to use let and const

global scope

Script tags and JS files are global variables

1. The attributes dynamically added to the window object are also global by default, which is not recommended!

2. Variables declared without using any keywords in the function are global variables and are not recommended!!!

3. Declare global variables as little as possible to prevent global variables from being polluted.

scope chain

Essentially the underlying variable lookup mechanism

When the function is executed, variables will be searched first in the current function scope.

If the current scope cannot be found, the parent scope will be searched level by level until the global scope.

Summarize:

1. The scopes of nested relationships are connected in series to form a scope chain.

2. Find variables in the same scope chain according to the rules from small to large.

3. The child scope can access the parent scope, but the parent scope cannot access the child scope.

JS garbage collection mechanism (GC)

Memory life cycle :

  1. Memory allocation: When we declare variables, functions, and objects, the system will automatically allocate memory for them.
  2. Memory usage: reading and writing memory, that is, using variable functions, etc.
  3. Memory recycling: After use, the garbage collector automatically reclaims the memory that is no longer used.

illustrate:

  • Global variables are generally not recycled (turn off page recycling)
  • In some cases, the value of a local variable will be automatically recycled if it is no longer needed.

**Memory Leak:** The memory allocated in the program is not released or cannot be released for some reason, which is called a memory leak.

JS garbage collection mechanism—algorithm description
  • Reference counting

There is a fatal problem: nested references (cyclic references)

If two objects refer to each other, although they are no longer used, the garbage collector will not recycle, resulting in a memory leak

  • mark-and-sweep

    Core idea: Scan objects from the root, use them if they can be found, and recycle those that cannot be found.

Closure

Closure = inner function + variables of outer function
Insert image description here

The function of the closure: to close the data, realize the data privacy, and the variables in the function can also be accessed from the outside.

Closures are useful, allowing functions to be associated with some data (environment) for other operations

Closure may cause memory leaks

The basic format of a closure:

     function outer(){
    
    
       let i =10;
        function fn(){
    
    
            console.log(i);
        }
       return fn;
    }
   const fun= outer(); 
    fun()

//简约写法
     function outer(){
    
    
       let i =10;
        return function(){
    
    
            console.log(i);
        }
    }
   const fun= outer(); 
    fun()
//闭包的应用: 统计函数调用的次数
let i=0;
function fn(){
    
    
    i++
    console.log(`函数被调用${
      
      i}`)
}
//值会有被篡改的风险

Insert image description here

//采用闭包的形式  实现数据的私有
function count(){
    
    
    let i=0;
    function fn(){
    
    
        i++
        console.log(`函数被调用${
      
      i}`);
    }
    return fn
}
const fun=count()//全局,不会被回收

Insert image description here

variable promotion

Promote all var declarations to the front of the current scope

Only declarations are promoted, assignments of undefined are not promoted

It is not recommended to use var declaration. There is no variable promotion for let and const.

Function advanced

Know the default values ​​of function parameters, dynamic parameters, and the details of the use of remaining parameters, improve the flexibility of function applications, know the syntax of arrow functions and the difference between ordinary functions

function promotion

  //1.会把所有函数声明提升到当前作用域的最前面
        //2.只提升函数声明,不提升函数调用
        fn()
        function fn(){
    
    
            console.log("函数提升");
        }
    //函数表达式必须先声明和赋值,才能调用  
//这样写是错误的。因为只提升函数声明,不提升函数赋值,会报错
  fun()
        var fun = function () {
    
    
            console.log("函数表达式");
        }

Insert image description here

Summarize:

  1. Function hoisting can make function declaration and calling more flexible
  2. Function expressions do not have hoisting
  3. function hoisting occurs in the same scope

Function parameters

Dynamic parameters

Entry point: arguments

        function getSum(){
    
    
            //arguments 动态参数 只存在于函数里面
            //是伪数组
            console.log(arguments);
        }
        getSum(2,3,4)

Insert image description here

 function getSum(){
    
    
            let sum=0;
            for(let i=0;i<arguments.length;i++){
    
    
                sum+=arguments[i]
            }
            console.log(sum)
        }
        getSum(2,3,4)
        getSum(1,2,3,4)
        getSum(2,2,3,4)

Insert image description here

Summarize:

  1. arguments is a pseudo-array that exists only in functions
  2. The role of arguments is to dynamically obtain the actual parameters of the function
  3. Through the for loop, the actual parameters passed in turn are obtained

Remaining parameters (advocated to use)

     function getSum(...arr) {
            console.log(arr);
        }
		//arr可以随便起名
        getSum(2, 3)
        getSum(1, 2, 3)

Insert image description here

The remaining parameters allow us to represent an indefinite number of parameters as an array

  1. ... is a grammatical symbol. As for the last function parameter, it is used to obtain redundant actual parameters. There is no need to use it...
  2. The remaining actual parameters obtained with the help of... are a real array (you can use various arr methods)

The main usage scenarios of remaining parameters: used to obtain redundant actual parameters

The difference between remaining parameters and dynamic parameters: dynamic parameters are pseudo arrays, and remaining parameters are real arrays

spread operator

        const arr=[1,2,3]
        //展开运算符可以展开数组
        console.log(...arr);

Insert image description here

The original array will not be modified

Typical application scenarios: finding the maximum (minimum) value of an array, merging arrays

   const arr=[1,2,3]
        //展开运算符可以展开数组
        // console.log(...arr);
        console.log(Math.max(1,2,3));
        console.log(Math.max(...arr));
         //结果都为3
        //实质上...arr===1,2,3
   		//合并数组
		const arr1=[1,2,3]
        const arr2=[4,5,6]
        const arr=[...arr1,...arr2]
        console.log(arr);

Summarize:

1. The main function of the expansion operator

​ Arrays can be expanded, and operations such as finding the maximum value of the array and merging arrays can be used

2. The difference between expansion operator and remaining parameters

​ The expansion operator is mainly array expansion

​The remaining parameters are used inside the function

Arrow functions (important)

**Purpose:** The purpose of introducing arrow functions is to write functions in a shorter way without binding this. The syntax of arrow functions is more concise than function expressions.

Usage scenarios: Arrow functions are more suitable for places where anonymous functions are originally needed.

basic grammar

Arrow functions primarily replace function expressions

When there is only one formal parameter, you can omit the parentheses

When there is only one line of code, we can omit the curly braces

Only one line of code can omit return

Arrow functions can return an object directly

    // //普通函数
        // const fn = function () {
    
    
        //     console.log(1, 2, 3);
        // }
        // fn()
        // //箭头函数主要替代函数表达式
        // const fn = () => {
    
    
        //     console.log(1, 2, 3);
        // }
        // fn()
        // //箭头函数传递参数
        // const fn=(x)=>{
    
    
        //     console.log(x);
        // }
        // fn(1)
        // //只有一个形参的时候,可以省略小括号
        // const fn=x=>{
    
    
        //     console.log(x);
        // }
        // fn(1)
        // //只有一行代码的时候,我们可以省略大括号
        // const fn=x=>console.log(x);
        // fn(1)
        //只有一行代码可以省略return
        // const fn=x=>x+x;
        // console.log(fn(1));
        //箭头函数可以直接返回一个对象
        const fn = (uname) => ({
    
     uname: uname })
        fn("赵丽颖")
        console.log(fn("赵丽颖"));

Summarize:

  1. Arrow functions are expression functions, so there is no function promotion
  2. The parentheses () can be omitted when the arrow function has only one parameter.
  3. When the arrow function body has only one line of code, you can omit the curly braces {} and it will automatically be returned as the return value.
  4. The parenthesized function body returns an object literal expression

arrow function parameters

Ordinary functions have dynamic parameters arguments

Arrow functions have no arguments dynamic parameters, but have remaining parameters...args

        //利用箭头函数来求和
        getSum = (...arr) => {
    
    
            let sum = 0;
            for (let i = 0; i < arr.length; i++) {
    
    
                sum += arr[i]
            }
            return sum;
        }
        console.log(getSum(1,2,3,4,5));

Summary: There are no arguments dynamic parameters in the arrow function, and the remaining parameters can be used

arrow functionthis

Before arrow functions, no new function defined its this value based on how it was called.

        //this指向window
        console.log(this);
        //普通函数中this指向window(即函数的调用者)
        function fn(){
    
    
        console.log(this);
        }
        window.fn()
        //对象方法里的this指向对象
        const obj={
    
    
            name:'andy',
            sayHi:function (){
    
    
                console.log(this);
            }
        }
        obj.sayHi()

The arrow function does not create its own this, it only inherits this from the upper level of its own scope chain.

        const obj={
    
    
            name:'andy',
            sayHi:()=>{
    
    
                console.log(this);
            }
        }
        obj.sayHi()
  const obj ={
    
    
            uname:"pink老师",
            sayHi:function(){
    
    
                console.log(this);
                let i=10
                const count =()=>{
    
    
                    console.log(this);
                }
                count()
            }
        }
        obj.sayHi()
//this指向都是obj

Summarize:

The arrow function does not create its own this, it only inherits this from the upper level of its own scope chain.

It is not recommended to use arrow functions in DOM event callback functions, especially when this is needed.

When the event callback function uses the arrow function, this is the global window.

Destructuring assignment

Destructuring syntax and classification, use destructuring concise syntax to quickly assign values ​​to variables

Array destructuring

Array destructuring is a concise syntax for quickly assigning unit values ​​of an array to a series of variables in batches.

  //基本语法:
        const arr=[100,60,80]
        //数组解构  赋值
        const [max,min,avg]=arr
        //就等价于如下赋值
        // const max =arr[0]
        // const max =arr[1]
        // const max =arr[2]
        console.log(max);
        console.log(min);
        console.log(avg);
 //典型应用   变量交互
       let a=1
       let b=2;//这里必须要加分号
        [b,a]=[a,b]
        console.log(a,b);

There are two situations where a semicolon must be added:

   //1.立即执行函数
        (function(){
    
     })();
        (function(){
    
     })();
        //2.使用数组的时候
        const str='pink';//如果这里不加分号,就会报错'pink'[1,2,3].map is not a function
        [1,2,3].map(function(item){
    
    
            console.log(item);
        })

Summarize:

1.What is the function of array destructuring assignment?

A concise syntax for quickly assigning the cell values ​​of an array to a series of variables in batches

2. In what two situations must a semicolon be added in front of JS?

  • Execute function immediately
  • Array destructuring

Replenish:

New ideas for string splicing:

String concatenation using map() and join() array methods

map can traverse the array to process data and return a new array

A map is also known as a mapping. Mapping is a term that refers to the relationship between the elements of two sets of elements that "correspond" to each other.

The key point of map is that it has a return value (returns an array), while forEach has no return value.

 const arr =['red','blue','pink'] 
        //数组map方法
        const newArr=arr.map(function(ele,index){
    
    
            console.log(ele);//数组元素
            console.log(index);//索引号
            return ele +"颜色"
        })
        console.log(newArr);
        

join method

     const arr =['red','blue','pink'] 
        //数组map方法
        const newArr=arr.map(function(ele,index){
            console.log(ele);//数组元素
            console.log(index);//索引号
            return ele +"颜色"
        })
        console.log(newArr);
        //数组join方法
        //把数组中的而所有元素转换成一个字符串
        console.log(newArr.join());//小括号为空,用逗号分割   red颜色,blue颜色,pink颜色
        console.log(newArr.join(''));//小括号为空,无分割     red颜色blue颜色pink颜色
        console.log(newArr.join('|'));//小括号为空,用|分割   red颜色|blue颜色|pink颜色
    

The details of array destructuring

  // const pc=['海尔','联想','小米','方正']
        // const [hr,lx,mi,fz]=['海尔','联想','小米','方正']
        // console.log(hr);
        // console.log(lx);
        // console.log(mi);
        // console.log(fz);
        // function getValue(){
        //     return [100,60]
        // }
        // const[max,min]= getValue()
        // console.log(max,min);
        //1.变量多,单元值少,undefined
        // const [a,b,c,d]=[1,2,3]
        // console.log(a);//1
        // console.log(b);//2
        // console.log(c);//3
        // console.log(d);//undefined
        //2.变量少,单元值多
        // const [a,b]=[1,2,3]
        // console.log(a);//1
        // console.log(b);//2
        //3.利用剩余参数 变量少,单元值多
        // const [a,b,...c]=[1,2,3,4]
        // console.log(a);//1
        // console.log(b);//2
        // console.log(c);//3,4
        //4.防止undefined传递,设个默认参数
        // const [a=0,b=0]=[1,2]
        // console.log(a);//1
        // console.log(b);//2
        //5.按需导入赋值
        // const [a,b,,d]=[1,2,3,4]
        // console.log(a);//1
        // console.log(b);//2
        // console.log(d);//4
        // //6.支持多维数组解构
        // const arr = [1, 2, [3, 4]]
        // console.log(arr[0]);
        // console.log(arr[1]);
        // console.log(arr[2]);
        // console.log(arr[2][0]);
        const [a, b, [c,d]] = [1, 2, [3, 4]]
        console.log(a);
        console.log(b);
        console.log(c);
        console.log(d);

Summarize:

When the number of variables is greater than the number of unit values, the excess variables will be assigned undefined

When the number of variables is less than the number of unit values, the remaining unit values ​​can be obtained through the remaining parameters..., but they can only be placed at the last position.

object deconstruction

Object destructuring is a concise syntax for quickly assigning object properties and methods to a series of variables in batches.

    //  //对象解构
        const obj={
            uname:'pink老师',
            age:18
        }
        //解构的语法
        // const {uname,age}={ uname:'pink老师', age:18}
        //等价于const uname=obj.uname
        //要求属性名和变量名必须一致
        // console.log(username);
        // console.log(age);
        //1.对象解构的变量名 可以重新改名 旧变量名:新变量名
        // const{uname:username,age}={ uname:'pink老师', age:18}
        // console.log(username);
        // console.log(age);
        //2.解构数组对象
        const pig=[
            {
                uname:'佩奇',
                age:6
            }
        ]
        const [{uname,age}]=pig
        console.log(uname);
        console.log(age);对象解构
        const obj={
            uname:'pink老师',
            age:18
        }
        //解构的语法
        const {uname,age}={ uname:'pink老师', age:18}
        //等价于const uname=obj.uname
        //要求属性名和变量名必须一致
        console.log(uname);
        console.log(age);

multi-level object destructuring

  const pig={
    
    
            uname:'佩奇',
            family:{
    
    
                mother:'猪妈妈',
                father:'猪爸爸',
                brother:'乔治'
            },
            age:6
        }
        //多级对象解构
        const {
    
    uname,family:{
    
    mother,father,brother}}=pig
        console.log(uname);
        console.log(mother);
        console.log(father);
        console.log(brother);

Multi-level array object destructuring

 const pig=[
        {
            uname:'佩奇',
            family:{
                mother:'猪妈妈',
                father:'猪爸爸',
                brother:'乔治'
            },
            age:6
        }
        ]
        const [{uname,family:{mother,father,brother}}]=pig
        console.log(uname);
        console.log(mother);
        console.log(father);
        console.log(brother);

Traversing the array forEach method (emphasis)

The forEach() method is used to call each element of the array and pass the element to the callback function

Main usage scenario: traverse each element of the array

        //forEach就是遍历 加强版的for循环
        const  arr=['red','green','pink']
        const result=arr.forEach(function(item,index){
    
    
            console.log(item);//数组元素 red green pink
            console.log(index);//索引号
        })
        console.log(result);//打印结果为undefined
```## 深入对象

### 创建对象的三种方式

**利用对象字面量创建对象**

```js
const o ={
    
    
            uname:'佩奇'
        }

Create an object using the function new object given by the system

 // const obj=new Object()
        // console.log(obj);
        // obj.name="pink老师"
        const obj=new Object({
    
    uname:"pink老师"})
        console.log(obj);

Create a custom constructor (encapsulate it)

     function Pig(name, age, gender) {
    
    
            this.name = name
            this.age = age
            this.gender = gender
        }
        //创建佩奇对象
        const Peppa=new Pig('佩奇',6,'女')
        const George=new Pig('佩奇',3,'男')
        const Mum=new Pig('猪妈妈',30,'女')
        const Dad=new Pig('猪爸爸',32,'男')
        console.log(Peppa);
        console.log(George);
        console.log(Mum);
        console.log(Dad);

Constructor

Constructor creates object

The constructor is a special function mainly used to initialize objects

Constructors are technically regular functions

But there are two agreements:

  1. Name starts with capital letter
  2. Can only be executed by the "new" operator
 //创建一个猪 构造函数
        function Pig(uname,age){
            this.uname=uname  //第一个uname属性//第二个uname形参
            this.age=age
        }
        console.log( new Pig('佩奇',6));

illustrate:

  1. The act of calling a function using the new keyword is called instantiation
  2. () can be omitted when there are no parameters when instantiating the constructor
  3. There is no need to write return inside the constructor, the return value is the newly created object
  4. The value returned by return inside the constructor is invalid, so do not write return
  5. new object() and new Date() are also instantiation constructors

Summarize:

What is the role of constructor? how to write?

  • Constructors are used to quickly create multiple objects
  • Functions starting with a capital letter

The behavior of a function called by the new keyword is called instantiation

There is no need to write return inside the constructor. The constructor automatically returns the created new object.

Instantiation execution process

  1. Create new empty object
  2. Constructor this points to the new object
  3. Execute the constructor code, modify this, and add new properties
  4. Return new object

Instance members & static members

The object created through the constructor is called an instance object, and the properties and methods in the instance object are called instance members (instance properties and instance methods)

illustrate:

  1. Pass in parameters to the constructor and create objects with the same structure but different values
  2. The instance objects created by the constructor are independent of each other and do not affect each other.

static member

Constructor properties and methods are called static members (static properties and static methods)

illustrate:

  • Static members can only be accessed by constructors
  • this in the static method points to the constructor

For example Date.now( ) Math.PI Math.random( )

Summarize:

1.Who are the instance members (properties and methods) written on?

The properties and methods of an instance object are instance members

Instance objects are independent of each other, and instance members are used by the current instance object.

2. Who writes static members (properties and methods)?

Constructor properties and methods are called static members

Static members can only be accessed through constructors

Built-in constructor

There are 6 main data types in JS

Basic data types: string, numeric value, Boolean, undefined, null

Reference type: object

   const str ="pink"
    //js 底层完成,把简单数据类型包装成了引用数据类型
        //const str =new String ('pink')
        console.log(str.length);
        const num=12
        console.log(num.toFixed(2));//num.toFixed()是保留几位小数

In fact, basic types such as strings, numbers, and Boolean also have special constructors. These are called packaging types.

Almost all data in JS can be created based on constructors

Built-in constructors are divided into reference types and wrapper types

reference type

Object、Array、RrgExp、Date等

type of packaging

String、Number、Boolean等

    // const str ="pink"
        //js 底层完成,把简单数据类型包装成了引用数据类型
        //const str =new String ('pink')
        console.log(str.length);
        const num=12
        console.log(num.toFixed(2));//num.toFixed()是保留几位小数

Object

Is a built-in constructor used to create ordinary objects

      const o={
    
    uname:'pink', age:18}
//1.获得所有的属性名
console.log(Object.keys(o));//返回数组['uname','age']
//获取所有的属性值
console.log(Object.values(o));//['pink',18]
//拷贝对象
const oo={
    
    }
Object.assign(oo,o)
console.log(oo);
//经常使用的场景:给对象添加属性
Object.assign(o,{
    
    gender:"女"})
console.log(o);

Array

is a built-in constructor used to create arrays

When creating an array, it is recommended to use literals instead of array constructors.

1. Common instance methods of arrays—core methods

method effect illustrate
forEach Traverse array Does not return an array, often used to find and traverse array elements
filter filter array Returns a new array, which returns the elements of the data group that meet the criteria
map Iterate over array Returns a new array, returns the array elements after processing, and wants to use the returned new array
reduce accumulator Return the result of cumulative processing, often used for summation, etc.
//数组reduce方法
//arr.reduce(function(上一次值,当前值){},初始值)
const arr =[1,5,6,8]
//1.没有初始值
// const total=arr.reduce(function(prev,current){
    
    
//     return prev+current
// })
// console.log(total);
//2.有初始值
const result=arr.reduce(function(prev,current){
    
    
    return prev+current
},10)
console.log(result);
//3.箭头函数的写法
 const total=arr.reduce((prev,current)=>prev+current,10)
 console.log(total);

2. The execution process of reduce

  1. If there is no starting value, the last value is the value of the first element of the array.
  2. Each time it loops, give the return value as the previous value for the next loop
  3. If there is a starting value, the starting value is used as the last value

There is no starting value, and the number of loops is one less than the number of array elements.

There is a starting value, and the number of loops is equal to the number of array elements.

How to use find

    // const  arr=['red','blue','green']
    //     const result=arr.find(function(item){
    //         return item==='blue'
    //     })//会将blue作为返回值返回
    //     console.log(result);
    //find最常使用的场景
    const  arr=[
        {
            name:'小米',
            price:1999
        },
        {
            name:'华为',
            price:3999
        }
    ]
    //找小米这个对象,并返回这个对象
    // arr.find(function(item){
    //     // console.log(item);
    //     // console.log(item.name);
    //     return item.name==='小米'
    // })
    const mi=arr.find(item=>item.name==="小米")
    console.log(mi);

How to use every

The every() method tests whether all elements in an array can pass the test of a specified function. Returns a boolean value

  //every()每一个是否都符合条件,如果都符合返回true,否则返回false
        const  arr=[10,20,30]
        const flag=arr.every(item=>item>=20)
        console.log(flag);

some usage

The some() method tests whether an array contains elements that can pass the test of a specified function. Returns a boolean value

    //some()至少有一个是否符合条件,如果有返回true,否则返回false
        const  arr=[10,20,30]
        const flag=arr.some(item=>item>=20)
        console.log(flag);

Insert image description here


        const spec={size:'40cm*40cm',color:'黑色'}
        //1.所有的属性值获取过来
        console.log(Object.values(spec));
        //2.转换为字符串 join('/')把数组根据分隔符转化为字符串
       console.log( Object.values(spec).join('/'));
       document.querySelector('div').innerHTML= Object.values(spec).join('/')

Convert pseudo array to real array

Static method Array.from( )

<body>
    <ul>
        <li>1</li>
        <li>2</li>
        <li>3</li>
    </ul>
    <script>
        const lis =document.querySelectorAll('ul li')
        console.log(lis);//获取过来的是伪数组NodeList(还有arguments获取的也是伪数组)
   // lis.pop();//伪数组无法使用pop删除方法
   const liss=Array.from(lis)
   console.log(liss);
   liss.pop()//真数组可以使用
   console.log(liss);
    </script>
</body>

Insert image description here

String

split

        //把字符串转化为数组,与join超级相似,根据分隔符将其分割成数组
        const str ='pink ,red'
        const arr=str.split(',')
        console.log(arr);
        const str1 ='2022-4-8'
        const arr1=str1.split('-')
        console.log(arr1);

The effect is as follows:
Insert image description here

substring()

   //字符串截取 substring(开始的索引号[,结束的索引号])
        const str='再也不用做核酸了'
        console.log(str.substring(5))//如果省略了结束索引号,默认取到最后
        console.log(str.substring(5,6))//截取的部分不包括结束索引

startsWith()

//startswith()用来判断当前字符串是否以另外一个给定的字符串开头,并根据判断结果返回true或false
        var str="To be, or not to be, that is the question."
        alert(str.startsWith("To be"));         //true
        alert(str.startsWith("not to be"));     //false
        alert(str.startsWith("not to be",10));  //true  加空格

includes

//includes 判断某个字符是否包含在一个字符串内
        var str="To be, or not to be, that is the question."
        console.log(str.includes('To be'));         //true
        console.log(str.includes('question'));      //true
        console.log(str.includes('nonexistent'));   //false
        console.log(str.includes('To be',1));       //false
        console.log(str.includes('To BE'));         //false
        console.log(str.includes('To b'));          //true

prototype chain

JS function-oriented programming

Constructor

Encapsulation is an important part of object-oriented thinking. JS object-oriented can achieve encapsulation through constructors.

Similarly, variables and functions are combined and data sharing can be realized through this, the difference is that the instance objects created with the help of constructors do not affect each other.

Summarize:

  • The constructor embodies the object-oriented encapsulation characteristics
  • Objects created by constructor instances are independent of each other and do not affect each other.

The constructor we learned before is easy to use, but there is a problem of wasting memory.

prototype

prototype

  • The functions assigned by the constructor through the prototype are shared by all objects
  • JS stipulates that each constructor has a prototype attribute that points to another object, so we also call it a prototype object.
  • This object can be mounted with functions, and object instantiation will not prototype the function multiple times, saving memory.
  • We can define those constant methods directly on the prototype object, so that all instances of the object can share these methods.
  • This in the constructor and prototype object both points to the instantiated object
  • Summarize:

A prototype is an object, we also call prototype a prototype object

Insert image description here

The role of prototypes:

  • Shared method
  • You can define those unchanged methods directly on the prototype object

This in the constructor and prototype points to the instantiated object

constructor property

Each prototype object has a constructor property

scenes to be used:

If there are multiple object methods, we can assign values ​​to the prototype object in the form of an object

But this will overwrite the original content of the constructor prototype object, so that the modified prototype object constructor no longer points to the current constructor. At this time, we can add a constructor to the modified prototype object pointing to the original constructor

       //constructor   构造函数
        //该属性指向该原型对象的构造函数,简单理解,就是指向我的爸爸,我是有爸爸的孩子
        function Star(){
    
    
        }
        // const ldh=new Star()
        // console.log(Star.prototype);
        // console.log(Star.prototype.constructor===Star);
        // Star.prototype.sing=function(){
    
    
        //     console.log('我会唱歌');
        // }
        // Star.prototype.dance=function(){
    
    
        //     console.log('我会跳舞');
        // }     //这样写显得繁琐
        console.log(Star.prototype); 
        Star.prototype={
    
      
            //从新指回创造这个原型对象的构造函数 
            constructor:Star,
            sing:function(){
    
    
                console.log('我会唱歌');
            },
            dance:function(){
    
    
                console.log('我会跳舞');
            },
        }
        console.log(Star.prototype); 

Insert image description here

Function: Points to the constructor of the prototype object

object prototype

The object will have a property __proto__ pointing to the prototype prototype object of the constructor. The reason why our object can use the properties and methods of the constructor prototype prototype object is because the object has the __proto__ prototype.

 function Star(){
    
     }
        const ldh=new Star()
        //对象原型__proto__ 指向该构造函数的原型对象
        console.log(ldh.__proto__);
        console.log(ldh.__proto__===Star.prototype);  //true
        //对象原型里面有constructor指向构造函数Star
        console.log(ldh.__proto__.constructor);

Notice:

  • __proto__ is a JS non-standard attribute
  • [[prototype]] has the same meaning as __proto__
  • Used to indicate which prototype object prototype the current instance object points to
  • There is also a constructor attribute in the __proto__ object prototype , which points to the constructor that created the instance object.

Insert image description here

Summarize:

1. What is the prototype? Where does it come from?

  • prototype (prototype object)
  • Constructors automatically have prototypes

2.Where is the constructor attribute? What does it do?

  • There are both prototype prototype and object prototype __proto__
  • Both point to the constructor of the created instance object/prototype

3. Where is the __proto__ attribute? To whom?

  • inside the instance object
  • Point to prototype prototype

prototypal inheritance

Inheritance is another feature of object-oriented programming. Through inheritance, the degree of code encapsulation is further improved. In JavaScript, most of the features of inheritance are realized by means of prototype objects.

Problems in prototypal inheritance:

Both use the same object at the same time. According to the characteristics of the reference type, they point to the same object, and modifying one will affect both

[External link picture transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the picture and upload it directly (img-YZOMRaKJ-1681011543044) (C:\Users\86184\Desktop\4.3-4.14\prototype inheritance problems. png)]

Ideas to solve the problem: Let Woman and Man point to different objects, but the content remains the same.

Solution to the problem: the object structure of the constructor new is the same but the objects are different

   // //男人,女人都继承了人这个特性
        // //继续抽取
        // const Person = {
    
    
        //     eyes: 2,
        //     head: 1
        // }

        //构造函数 new出来的对象 结构一样 但对象不一样
        function Person(){
    
    
            this.eyes=2
            this.head=1
        }
        //女人 构造函数  想要继承Person
        function Woman() {
    
    
            // this.eyes = 2
            // this.head = 1
        }
        //Women 通过原型来继承Person
        // Woman.prototype = Person
        Woman.prototype =new Person()
        //指回原来的函数
        Woman.prototype.constructor = Woman
        //给女人添加一个方法  生孩子
        Woman.prototype.baby=function(){
    
    
            console.log('宝贝');
        }//这样添加之后,男女都有baby,麻烦大了
        //出现该问题的原因
        //男人和女人都同时使用了同一个对象,根据引用类型的特点,他们指向同一个对象,修改一个就会都影响
        //解决问题的思路:让Woman和Man指向的对象不同,内容依然相同
        //解决问题的方法:构造函数 new出来的对象 结构一样 但对象不一样 
        const red = new Woman()
        console.log(red);
        console.log(Woman.prototype);//指回了原来的函数,既继承了属性,又有了constructor
        // console.log(red.eyes);

        //男人 构造函数   想要继承Person
        function Man() {
    
    
            // this.eyes = 2
            // this.head = 1
        }
        //Man通过原型继承Person
        Man.prototype=new Person() 
        //指回原来的函数
        Man.prototype.constructor=Man 
        const pink = new Man()
        console.log(pink);
        console.log(Man.prototype);

prototype chain

The inheritance based on the prototype object is that the prototype objects of different constructors are associated together, and the relationship of this association is a chain structure. We love the chain structure of the prototype object as the prototype chain.

Insert image description here
Insert image description here
Insert image description here

Pasting a blog here, I think it’s pretty good.

(37 messages) JavaScript complete prototype chain diagram_js prototype chain diagram_Dandan boom's blog-CSDN blog

Give array extension method

 //自己定义 数组扩展方法 求和  和  最大值
        //1. 我们定义的这个方法,任何一个数组实例对象都可以使用
        //2. 自定义的方法写(挂载)到 数组.prototype身上

        //求最大值
        // const arr=[1,2,3]
        // Array.prototype.max=function(){
    
    
        //     //展开运算符
        //     return Math.max(...this)
        // }
        // console.log(arr.max());

        //求最小值
        // const arr=[1,2,3]
        // Array.prototype.min=function(){
    
    
        //     return Math.min(...this)
        // }
        // console.log(arr.min());

        
        //求和 方法
        const arr=[1,2,3]
        Array.prototype.sum=function(){
    
    
           return this.reduce((prev,item)=>prev+item,0)
        }
        console.log(arr.sum());

Guess you like

Origin blog.csdn.net/L19541216/article/details/129970487