[Front-end learning diary] Javascript process control statement & object Object & function

1. Process control statement

Programs are executed sequentially from top to bottom, and
the sequence of program execution can be changed through flow control statements, or a certain segment of the program can be executed repeatedly.

1. Conditional branch statement

1.1 if statement

语法一: if(条件表达式)
 {
    
       	语句...   }

Execution process:
When the if statement is executed, the conditional expression will be evaluated and judged first.
If the value is true, the statement after the if will be executed.
If the value is false, the statement will not be executed.

1.2 else-if statement

语法二:

if(条件表达式){
    
      
	语句...  
}else{
    
      
	语句...  
}

Execution process:
When the if...else statement is executed, the conditional expression will be evaluated and judged.

  • If the value is true, execute the statement after the if
  • If the value is false, execute the statement after else

1.3 Multiple else-if statements

语法三:

if(条件表达式){
    
      
	语句...  
}else if(条件表达式){
    
      
	语句...  
}else if(条件表达式){
    
      
	语句...  
}else if(条件表达式){
    
      
	语句...  
}else{
    
      
	语句...  
}

Execution process
When the if...else if...else statement is executed, the conditional expressions will be evaluated and judged sequentially from top to bottom.

  • If the judgment result is true, the statement after the current if is executed, and the statement ends after the execution is completed.
  • If the judgment result is false, continue to judge down until it finds true.
  • If all conditional expressions are false, execute the statement after else

switch statement
syntax:

switch(条件表达式){
    
      
	case 表达式:  
		语句...  
		break;  
	case 表达式:  
		语句...  
		break;  
	default:  
		语句...  
		break;  
}

Execution process:
When the switch...case... statement is executed, it will sequentially compare the value of the expression after the case with the value of the expression after the switch.

  • If the result of the comparison is false, the comparison continues downward. If the comparison result is true, the code is executed downwards from the current case.
  • If all case judgment results are false, the code will be executed from default.

2. Loop statement

Through the loop statement, some statements can be repeatedly executed multiple times
while loop
Syntax:

while(条件表达式){
    
      
    语句...  
}

Execution process:
When the while statement is executed, it will first evaluate and judge the conditional expression.

  • If the judgment result is false, terminate the loop
  • If the judgment result is true, the loop body
    is executed. After the loop body is executed, continue to evaluate and judge the conditional expression, and so on

2.1 do...while loop

grammar:

do{ statement... }while (conditional expression) execution flow do...while is executed, the loop body after do will be executed first, and then the conditional expression will be judged. If the judgment result is false, the loop will be terminated. If the judgment result is true, continue to execute the loop body, and so on





Differences from while:
while: judge first and then execute
do...while: execute first and then judge
do...while can ensure that the loop body is executed at least once.

2.2 for loop

grammar:

for(①初始化表达式 ; ②条件表达式 ; ④更新表达式){
    
      
    ③语句...  
}

Implementation process:

  1. First execute ① initialization expression to initialize a variable
  2. Then evaluate the ② conditional expression, and if it is false, terminate the loop
  3. If the judgment result is true, execute the loop body of ③
  4. After the loop body is executed, execute ④ to update the expression to update the variable.
  5. The update expression is executed and repeated②

2.3 Infinite loop

while(true){
    
      

}  

for(;;){
    
      

}

2. Object

  • Objects are reference data types in JS
  • An object is a composite data type in which multiple different data can be stored
  • Type of properties
    When using typeof to check an object, object will be returned

1. Classification of objects

1.1 Built-in objects

  • Objects defined by the ES standard can be used in any ES implementation
  • 比如:Math String Number Boolean Function Object….

1.2. Host object

  • The objects provided by the JS operating environment mainly refer to the objects provided by the browser at present.
  • Such as BOM DOM

1.3. Custom objects

  • Objects created by developers themselves

2. Create objects

method one:

var obj = new Object();

Method 2:

var obj = {
    
    };

3. Add properties to the object

grammar:

对象.属性名 = 属性值;
对象[“属性名”] = 属性值; //这种方式能够使用特殊的属性名

There is no requirement for the attribute name of the object, and there is no need to follow the specification of the identifier, but in the development, try to write according to the requirements of the identifier .
Attribute values ​​can also be of any data type.

4. Read the properties in the object

grammar:

Object.PropertyName
Object["PropertyName"] // "PropertyName"

It can be a string constant or a string variable.
If you read an attribute that is not in an object, it will not report an error, but return an undefined

5. Delete the attribute in the object

grammar:

delete object.property name
delete object["property name"]

6. traverse

Use in to check whether the object contains the specified property
Syntax:

"property name" in object

  • Returns true if the property is present in the object
  • return false if none

Loop through the object's own and inherited enumerable properties (excluding Symbol properties).

var obj = {
    
    '0':'a','1':'b','2':'c'};  
  
for(var i in obj) {
    
      
     console.log(i,":",obj[i]);  
}

​Use
object literals to add properties directly to the object when creating the object
Syntax:

var obj = {
    
      
    属性名:属性值,  
    属性名:属性值,  
    属性名:属性值
}

Primitive Data Types and Reference Data Types
Primitive Data Types

String
Number
Boolean
Null
Undefined

Refer to the data of the data type
Object
basic data type, and the variable is directly saved its value.
Variables are independent of each other, modifying one variable will not affect other variables.
Data of the reference data type, the variable is the reference (memory address) of the saved object.
If multiple variables point to the same object, modifying the properties of one variable will affect other variables.
When comparing two variables, for the basic data type, the value is compared,
for the reference data type, the address is compared, and the addresses are the same.

3. Function

A function is also an object, and it also has the function of an ordinary object (it can have attributes).
Some code can be encapsulated in the function, and the function can be called to execute the code when needed. When
checking a function with typeof, it will return function

1. Create a function

function declaration

function 函数名([形参1,形参2...形参N]){
    
      
    语句...  
}

function expression

var 函数名 = function([形参1,形参2...形参N]){
    
      
    语句...  
};

2. Call the function

Syntax: function object ([actual parameter 1, actual parameter 2...actual parameter N]);

fun() sum() alert() Number() parseInt()

When we call a function, the code encapsulated in the function will be executed in the order in which it was written

3. Execute the function immediately

After the function is defined, it is called immediately. This kind of function is called an immediate execution function.
Immediate execution functions are often only executed once.

(function(a,b){
    
      
    console.log("a = "+a);  
    console.log("b = "+b);  
})(123,456);

4. Traversing objects

for(var v in obj){
    
      
    document.write("property:name ="+v+"value="+obj[v]+"<br/>" );  
}

5. Formal parameters and actual parameters

formal parameters: formal parameters

  • When defining a function, you can define one or more formal parameters in (), use between formal parameters, and separate
  • Defining a formal parameter is equivalent to declaring the corresponding variable in the function but not assigning a value.
  • Formal parameters are assigned values ​​at call time.

Actual parameter: the actual parameter

  • When calling a function, you can pass actual parameters in (), and the passed actual parameters will be assigned to the corresponding formal parameters.
  • When calling a function, the JS parser will not check the type and number of actual parameters, and can pass a value of any data type.
  • If the number of actual parameters is greater than the formal parameters, the redundant actual parameters will not be assigned,
  • If the number of actual parameters is less than the formal parameters, the formal parameters without corresponding actual parameters will be assigned the value undefined

6. Return value

is the result of function execution

Use return to set the return value of the function.

Syntax: return value;

This value will become the return value of the function, and the return value can be received through a variable

  • The code behind the return will not be executed. Once the return statement is executed, the function will exit immediately.
  • Return can be followed by any type of value, which can be a basic data type or an object.
  • If return is not followed by a value, or return is not written, the function returns undefined by default.

7.break、continue和return

break exits the loop
continue skips the current loop
return exits the function

Parameters, the actual parameters of the function can also be any data type.

8. Method

A function can be set as a property of an object.
When a property of an object is a function,
we call the function a method of the object.
Object.MethodName();
FunctionName()

Function properties and methods

call()
apply()

These two methods are methods of function objects that need to be called through the function object
Through the two methods, the function can be called directly, and the this in the function can be specified through the first actual parameter

The difference is that call directly passes the actual parameters of the function, while apply needs to encapsulate the actual parameters into an array and pass them

8.1 arguments

arguments is similar to this, they are implicit parameters in the function.
arguments is an array-like element, which is used to encapsulate the actual parameters during the execution of the function.
So even if the formal parameters are not defined, the actual parameters can be used through
arguments A property callee represents the currently executing function object

8.2 this (the object that called the function)

this is the context object of the function, and it will execute different objects according to the calling method of the function

  1. When called as a function, this is window
  2. When called as a method, this is the object calling the method
  3. When called as a constructor, this is the newly created object
  4. When calling with call and apply, this is the specified object
  5. In the global scope this represents window

9. Scope

Scope is simply the scope of a variable.
There are two types of scopes in JS:

9.1 Global scope

Code written directly in the script tag runs in the global scope

The global scope is created when the page is opened and destroyed when the page is closed.

There is a global object window in the global scope, and the window object is provided by the browser.

Can be used directly in the page, it represents the entire browser window.

  • Variables created in the global scope are saved as properties of the window object
  • Functions created in the global scope are saved as methods of the window object
  • Variables and functions created in the global scope can be accessed anywhere on the page.
  • Variables in the global scope can also be accessed in the function scope.
  • Try not to create variables globally

9.2 Function scope

A function scope is a scope created when a function is executed, and a new function scope is created every time a function is called.
Function scope is created when the function is executed and destroyed when the function execution ends.
Variables created in function scope cannot be accessed globally.
When a variable is used in a function scope, it will first look for it in its own scope,
if it is found, it will be used directly, if it is not found, it will be searched in the upper level scope, if it is found,
it will be used, if not found Then keep looking upwards, always

Variable declaration ahead of time
In the global scope, variables declared with the var keyword will be declared before all code is executed, but will not be assigned a value.

So we can use variables before variable declaration. But variables declared without the var keyword will not be declared ahead of time.
In the function scope, it also has this feature. Variables declared with the var keyword will be declared before all codes of the function are executed.
If the variable is not declared with the var keyword, the variable will become a global variable

Function declaration ahead of time
In the global scope, the function created using the function declaration (function fun(){}) will be created before all code execution, that is,
we can call the function before the function declaration, but using the function The function created by the expression (var fun = function(){}) does not have this feature.
In the function scope, the function created using the function declaration will be created before all the code in the function is executed.

9.3 this (context object)

Every time we call a function, the parser passes a context object as an implicit parameter into the function.
Use this to refer to the context object. Depending on the calling form of the function, the value of this is also different.

point to the current object

Different cases of this:

  1. When called as a function, this is window
  2. When calling in the form of a method, this is the object calling the method
  3. When called as a constructor, this is the newly created object

9.4 Constructors

A constructor is a function specially used to create objects.
A constructor can also be called a class. An
object created through a constructor is called an object when an instance of the constructor
is created through the same constructor. We call it A class of object
constructor is an ordinary function, but its calling method is different.
If it is called directly, it is an ordinary function
. If it is called by new, it is a constructor

example:

function Person(name , age , gender){
    
      
    this.name = name;  
    this.age = age;  
    this.gender = gender;  
    this.sayName = function(){
    
      
        alert(this.name);  
    };  
}

The execution flow of the constructor:

  1. create a new object
  2. Use the new object as the function's context object (this)
  3. Execute the code in the function
  4. Return the newly created object

instanceof is used to check whether an object is an instance of a class

Syntax:
object instanceof constructor

If the object is an instance of the constructor, it returns true, otherwise it returns false
Object is the ancestor of all objects, so doing instanceof with any object and Object will return true


The attribute for...in syntax in the enumeration object
:

for(var 属性名 in 对象){
    
      
  
}

The loop body of the for...in statement is executed multiple times. There are several attributes in the object and it will be executed several times.
Each time, an attribute name is assigned to the variable we defined, and we can use it to obtain the attributes in the object.

10. *Prototype

All JavaScript objects inherit properties and methods from a prototype:

Date objects inherit from Date.prototype.
Array objects inherit from Array.prototype and
Person objects inherit from Person.prototype.

All objects in JavaScript are instances of Object at the top of the prototype chain.

JavaScript objects have a chain pointing to a prototype object .

After creating a function, the parser will add a number prototype to the function by default. The
prototype attribute points to an object, which we call a prototype object.
When a function is used as a constructor, the object it creates will have an implicit property that executes the prototype object.

This implicit property can be accessed through object.__proto__.

The prototype object is equivalent to a public area, and all objects created through the same constructor can usually access the same prototype object.
We can uniformly add the common properties and methods in the object to the prototype object,
so that we only need to add it once to make all objects available.

When trying to access a property of an object, it searches not only on the object, but also on the object's prototype, and on the prototype of the object's prototype, and so on until it finds a property with a matching name or reaches the prototype the end of the chain.

Date object, Array object, and Person object inherit from Object.prototype.

Add properties and methods

Use the prototype attribute to add new properties and methods to the object's constructor.

Sometimes we want to add new properties or methods to all existing objects.

Also, sometimes we want to add properties or methods in the object's constructor.

You can add new properties to an object's constructor using the prototype property:

function Person(first, last, age, eyecolor) {
    
    
  this.firstName = first;
  this.lastName = last;
  this.age = age;
  this.eyeColor = eyecolor;
}

Person.prototype.nationality = "English";
Of course, we can also use the prototype attribute to add new methods to the object's constructor:

function Person(first, last, age, eyecolor) {
    
    
  this.firstName = first;
  this.lastName = last;
  this.age = age;
  this.eyeColor = eyecolor;
}
 
Person.prototype.name = function() {
    
    
  return this.firstName + " " + this.lastName;
};

hasOwnProperty()

This method can be used to check whether the object itself contains a property

Syntax:
object.hasOwnProperty("property name")

toString method

When we print an object directly on the page, the event is the return value of the toString() method of the output object

If we want not to output [object Object] when outputting an object, we can add a toString() method to the object

//Modify the toString of the Person prototype

Person.prototype.toString = function(){
    
      
	return "Person[name="+this.name+",age="+this.age+",gender="+this.gender+"]";  
};

11. Garbage Collection (GC)

Just like garbage will be generated when people live for a long time, garbage will also be generated during the running of the program. After the accumulation of
too much garbage, the running speed of the program will be too slow,
so we need a garbage collection mechanism to handle the running of the program Garbage generated during the process
When an object does not have any variables or attributes to refer to it, we will never be able to operate the object at this time. At this time,
this object is a garbage. Too many such objects will occupy a large amount of memory space, resulting in Programs run slower,
so this garbage has to be cleaned up.
There is an automatic garbage collection mechanism in JS, which will automatically destroy these garbage objects from memory.
We don't need and can't perform garbage collection operations.
All we need to do is set the objects that are no longer used to null.

Guess you like

Origin blog.csdn.net/P9ulp/article/details/126706013