JS review (Day02)

Object-oriented

Is a kind of programming idea, the programming language that realizes this kind of idea, we can also be called object-oriented

Three characteristics:

Encapsulation: hide internal details and only develop external operation interfaces (methods of objects)

Inheritance: An object can inherit the members of another object and expand without changing the other object.

Polymorphism: The same operation acting on different objects will produce different results. (Variable storage in js)

Object:

definition:

Realized by {}, the member of the object is a key-value pair, and multiple members are separated by (comma).

Empty object:

var o1 = {
    
    }

Single member object

var o2 = {
    
    
        name:"jack"
    }

Multiple member objects

var o3= {
    
    
        name:"jack",
        age:18,
        sex:'男'
        ......
    }

Object with members and methods

var o4 ={
    
    
	name:'angle',
	age:25,
	gender:'女',
	say:function(){
    
    
		console.log('hello')
	}
}

Access to the members of the object, object name, member name.

Traversal of object members

for… in to complete

for(obj in o4)

Emphasis: Copying (duplication) of objects

Shallow copy:

The shortcut of the original object is copied to the copy object (the object itself is not copied), and the two objects point to the same memory space

**Advantages: **Can save memory space

Insert picture description here

Deep copy:

Really create a copy of an object, copy this copy to another object

Insert picture description here

// 深拷贝
function deepCopy(obj){
    
    
    var p2 = {
    
    }
    for(var k in obj){
    
    
        //遍历obj的成员,判断obj[k]的类型,用到了递归
        p2[k] = (typeof obj[k] === 'object')?deepCopy(obj[k]):obj[k]
    }
    return p2
}

var p3 = {
    
    
    name:'jack',
    age:18,
    subject:{
    
    
        name:['html','css','javascript']
    }
}

var p4 = deepCopy(p3)
console.log(p3 === p4)

p4.name = '猪猪'
console.log(p3)
console.log(p4)

Constructor

It is another way of javascript to create objects, which is different from {}: it can create several objects with the same characteristics.

function factory(age,name){
    
    
    var obj = {
    
    }
    obj.name = name;
    obj.age = age;

    return obj;
}

var o1 = factory('曹操',24)
var o2 = factory('刘备',30)

console.log(o1)
console.log(o2)

Insert picture description here

JavaScript built-in constructor

new 构造函数名([形参1,形参2])

Object:new Object()
String:new String('123456')
Date:new Date('2021-03-12')
......

Access the object's constructor:

Constructor through the object

对象名.constructor

Private member

In the constructor, the variable defined with var, we call it a private member, the private member cannot 对象名.成员名be accessed

var name = ‘javaScript’

To access private members, a function must be nested in the constructor to return the value of the private member

function Person(){
    
    
    var name = 'javaScript'
    //必须加this
    this.getName = function(){
    
    
        return name
    }
}
var o1 = new Person();
console.log(o1.getName())

This keyword

It is mainly used in functions. Depending on the environment in which the function is called, the point of this will be different.

1. When using the new keyword to call a function as a constructor:

This inside the constructor points to the newly created object

Insert picture description here

At this time this points to O1

2. When calling a function directly through the function name, This in the function refers to the global object

This in the browser points to the window object

3. If the function is called as a method, this points to the object.

Change the direction of This

apply()

call()

function method(){
    
    
    console.log(this.name)
}
method.apply({
    
    name:'张三'})
method.call({
    
    name:'李四'})

The first this points to Zhang San, the second this points to Li Si

Commonly used built-in objects

String: String object

Number: Numerical object

Math: Mathematical operation object

Date: date and time object

Array: Array object

Prototype and inheritance

Every time a function is created, an object will follow, and the function points to the object through the prototype property.

Prototype: also known as prototype object, refers to the object corresponding to the method

How to implement inheritance through prototypes?

1. Traditional inheritance, an object does not have a certain property or method, but it can be obtained from another pair

function Person(name){
    
    
    this.name = name
}
Person.prototype.sayHello = function(){
    
    
    console.log('Hello'+this.name)
}
var p1 = new Person('关羽')
p1.sayHello()

Insert picture description here

2. Replace the prototype object to achieve inheritance, replace the prototype object of the constructor with a new object, then the object created based on the constructor will inherit the new prototype object.

function Person(){
    
    }

Person.prototype = {
    
    
    sayHello:function(){
    
    
        console.log('你好,我是新对象')
    }
}

var p = new Person()
p.sayHello()

Insert picture description here

3. Use object.create() to achieve inheritance

var obj = {
    
    
    sayHello:function(){
    
    
        console.log('我是一个带有sayHello方法的对象')
    }
}
//相当于newObj继承了obj的功能
var newObj = Object.create(obj)

newObj.sayHello()
// __proto__是寻找它的原型对象
console.log(newObj.__proto__ === obj)

Insert picture description here

Prototype chain

Write picture description here

img

Objects have prototype objects, and prototype objects also have their own prototype objects. Such a chain structure is called a prototype chain.

The essence of a function is an object, so a function also has a constructor. The constructors of all built-in objects are function functions

console.log(String.constructor)
console.log(Number.constructor)

Insert picture description here

The prototype object of the prototype object: The prototype of the object is obtained through 对象.constructor.prototype, because the attribute of the constructor points to the constructor to form a loop, and the prototype of the prototype object cannot be accessed. In order to solve this problem, some browsers have added new properties __proto__to the object to point to the prototype of the prototype object (Firefox, Google)

The structure of the prototype chain

Custom functions, as well as built-in functions such as Object, String, Number, etc., are all created by the function function, which is created by the function function itself

Each constructor has a prototype object, the constructor points to the prototype object through the prototype attribute, and the prototype object points to the constructor through the constructor attribute.

The instance object created by the constructor function inherits from the prototype object of the constructor function, and the prototype object __proto__can be directly accessed through the properties of the instance object

The prototype object of the constructor inherits from the prototype object of Object, and the __proto__property of the prototype object of Object is null

The instanceof operator is used to detect whether an object’s prototype chain contains the object represented by the prototype property of a certain constructor.

Array

A collection of data of the same type

Create an array

Create using array object

var arr = new Array()

var arr = new Array(‘a1’,‘a2’,‘a3’)

Use [] to create an array

var tmp = [1,2,3]

Basic operation of array

Get the length of the array

The Array object provides the length property, which stores the length of the array.

Array length = array index + 1

Array access and traversal

Access array elements

数组名[索引]

Traverse

for… in… loop to complete

Array add, delete, modify

Add: Array name.push(data) Array name.unshift(data)

Modification: array name [index] = value

Delete: delete array name [subscript]

Array sort

Bubble Sort:

// 冒泡排序 12 升序排列
var arr = [10,22,1,24,4,2,13,5,7,3,0,99]
console.log('待排序数组是'+arr)

for(var i=0;i<arr.length;i++){
    
    
    for(var j=0;j<arr.length-i;j++){
    
    
        if(arr[j]>arr[j+1]){
    
    
            // var flag = arr[j+1];
            // arr[j+1] = arr[j];
            // arr[j] = flag
            [arr[j],arr[j+1]] = [arr[j+1],arr[j]]
        }
    }
}
console.log("排序后的数组为"+arr)

Insert picture description here

Insertion sort:

Traverse forward from the last element

// 插入排序
var arr = [12,1,15,46,23,45,34,22,345]
console.log('需排序数组'+arr)

for (var i = 0;i<arr.length;i++){
    
    
    for(var j = i;j>0;j--){
    
    
        if(arr[j-1]>arr[j]){
    
    
            [arr[j-1],arr[j]] = [arr[j],arr[j-1]]
        }
    }
}

console.log('排序后的为'+arr)

Select sort

for(var i=0;i<arr.length;i++){
    
    
    var min = arr[i];
    var k = i;
    for(var j=i+1;j<arr.length;j++){
    
    
        if(min > arr[j]){
    
    
            min = arr[j];
            k = j;
        }
    }
    if(k !=i){
    
    
        [arr[i],arr[k]] = [arr[k],arr[i]]
    }
}

Commonly used array operation methods

Methods of stack and queue:

push()— Add new elements to the end of the array and return the new length of the array

unshift()— Add a new element to the beginning of the array and return the new length of the array

pop()— Remove an element from the end of the array and return undefined if the array is null

shift()— Move out from the beginning of the array and return an element, if the array is null, return undefined

Search method:

includes()—Determine whether there is an element in the array, return true if there is, false if not

indexof()-returns the first index of a given element

lastIndexOf()—returns the last index value (subscript) of the given element in the array

Array.IsArray()—Judging whether the passed value is an array, return: yes -true, not -false

Array to string:

join()—Connect all elements in the array into a string

toString()—Convert the array to a string

other:

sort()—sort the array and return the array (default ascending order)

fill()—Fill all elements in the specified subscript range in the array with a fixed value

reverse()—reverse the position of all elements in the array

splice()—Add or delete elements to the array within the specified range

cancat()-Combine two or more arrays

slice()—Copy the array in the specified range to a new array

Guess you like

Origin blog.csdn.net/rraxx/article/details/114728694