Front end development foundation (JavaScript foundation III)

Posted by harryman100 on Thu, 20 Jan 2022 10:29:20 +0100

1, Scope

1. Global scope:

It acts on the environment of all code execution (inside the whole script tag) or an independent js file.

2. Local scope:

The code environment acting on the function is the local scope. Because it is related to functions, it is also called function scope.

3. JS has no block level scope:

  • The block scope is included by {}.
  • In other programming languages (such as Java, c# etc.), variables created in if statements and loop statements can only be used in this if statement and loop statement, such as the following java code:
if(true){
  int num = 123;
  system.out.print(num);  // 123
}
system.out.print(num);    // report errors

No block level scope in Js:

if(true){
  var num = 123;
  console.log(123); //123
}
console.log(123);   //123

4. Scope of variable:

(1) Global variables:

Variables declared under the global scope are called global variables (variables defined outside the function)
  • Global variables can be used anywhere in the code
  • The variables declared by var under the global scope are global variables
  • In special cases, variables that are not declared with var in the function are also global variables (not recommended)

(2) Local variables:

Variables declared under the local scope are called local variables (variables defined inside the function)
  • Local variables can only be used inside the function
  • The variables declared by var inside the function are local variables
  • The formal parameters of a function are actually local variables

(3) Differences between global variables and local variables:

  • Global variable: it can be used anywhere. It will be destroyed only when the browser is closed, so it takes up more memory
  • Local variable: only used inside the function. When the code block in which it is located is executed, it will be initialized; The contemporary code block will be destroyed after running, so it saves more memory space

5. Scope chain:

As long as the code is in a scope, it is written in the local scope inside the function, and it is not written inside any function, that is, it is in the global scope; If there is a function in the function, it is in this scope
 Another scope can be born; According to in**[Internal functions can access external function variables]**This mechanism, which uses chain search to determine which data can be accessed by internal functions, is called scope chain

6. Pre resolution:

JavaScript The code is generated by the JavaScript Parser to execute. JavaScript The parser is running JavaScript Code is divided into two steps: pre parsing and code execution.
Pre parsing is also called variable and function promotion.
Variable promotion (variable pre parsing): the declaration of the variable will be promoted to the top of the current scope, and the assignment of the variable will not be promoted.

(1) Pre parsing of variables:

  • Pre parsing: under the current scope, before JS code execution, the browser will declare or define variables with var and function declarations in memory by default.
  • Code execution: execute JS statements from top to bottom.
  • Pre parsing completes the declaration of variables and functions before code execution.

(2) Function pre parsing:

Function promotion: the declaration of the function will be promoted to the top of the current scope, but the function will not be called.
fn();
var  fn = function() {
    console.log('I don't think so');
}
Result: "error prompt" fn is not a function"
Explanation: the variable declaration will be promoted before the execution of this code, fn The value after promotion is undefined;and fn Call is in fn Before being assigned to the function body, at this time fn The value of is undefined,Therefore, it cannot be called correctly

2, Object:

1. Create object:

(1) To create an object with literals:

It's curly braces { } It contains the attributes and methods of expressing this specific thing (object);{ } It is expressed in the form of key value pairs 
  • Key: equivalent to attribute name
  • Value: equivalent to attribute value and can be any type of value (numeric type, string type, boolean type, function type, etc.)
var star = {
    name : 'pink',
    age : 18,
    sex : 'male',
    sayHi : function(){
        alert('Hello, everyone~');
    }
};
  • Object properties

The "key" in the "key value pair" in which specific data is stored in the object is called the attribute of the object, that is, the item in which specific data is stored in the object

Access object properties:
console.log(star.name)     // Call name attribute
console.log(star['name'])  // Call name attribute
  • Object method

Method call in object: object Method name (). Note that the method name must be followed by parentheses

star.sayHi();              // When calling the sayHi method, be careful not to forget to bring the following parentheses
  • summary
Attributes are part of an object, variables are not part of an object, and variables are separate containers for storing data
	Variable: independent declaration and assignment, independent existence
	Attribute: the variables in an object are called attributes and do not need to be declared. They are used to describe the characteristics of the object
 A method is a part of an object, a function is not a part of an object, and a function is a container that encapsulates operations separately
	Function: it exists separately through "function name"()"Can be called
	Method: the function in the object is called a method. The method does not need to be declared. Use "object".Method name()"Methods can be called to describe the behavior and function of the object.

(2) Creating objects with new objects

  • Create an empty object
var andy = new Obect();

Create an Object through the built-in constructor Object. At this time, the andy variable has saved the created empty Object

  • Add properties and methods to an empty object
andy.name = 'pink';
andy.age = 18;
andy.sex = 'male';
andy.sayHi = function(){
    alert('Hello, everyone~');
}

(3) Creating objects with constructors

  • Constructor
    Is a special function, which is mainly used to initialize objects, that is, to assign initial values to object member variables. It is always used with the new operator. We can extract some public attributes and methods from the object and encapsulate them into this function
Encapsulation format of constructor
function Constructor name(Formal parameter 1,Formal parameter 2,Formal parameter 3) {
     this.Property name 1 = Parameter 1;
     this.Property name 2 = Parameter 2;
     this.Property name 3 = Parameter 3;
     this.Method name = Function body;
}
Call format of constructor
var obj = new Constructor name(Argument 1, argument 2, argument 3)
Constructor conventions are capitalized.
The attributes and methods in the function need to be added in front this ,Represents the properties and methods of the current object.
Not required in constructor return Returns the result.
When we create objects, we must use new To call the constructor.

2. Traversal object

The for... in statement is used to perform a circular operation on the attributes of an array or object.

for (variable in Object name) {
    // Execute code here
}

The variable in the syntax is user-defined. It needs to comply with the naming convention. Usually, we will write this variable as k or key.

for (var k in obj) {
    console.log(k);      // k here is the attribute name
    console.log(obj[k]); // obj[k] here is the attribute value
}

3, Built in objects:

There are three kinds of objects in JavaScript: custom object, built-in object and browser object. The first two objects are the basic content of JS and belong to ECMAScript; The third browser object is unique to JS. JS API explains that built-in objects refer to some objects of JS language. These objects are used by developers and provide some common or most basic and necessary functions (properties and methods). The greatest advantage of built-in objects is to help us develop quickly

1. Math object

The Math object is not a constructor, it has properties and methods of mathematical constants and functions. Math related operations (absolute value, rounding, maximum value, etc.) can use members in math.

	Property, method name											function
	Math.PI								PI
	Math.floor()						Round down
	Math.ceil()							Round up
	Math.round()						Note that the rounding plate shall be rounded to the nearest place -3.5 The result is -3
	Math.abs()							absolute value
	Math.max()/Math.min()				Find the maximum and minimum values
	Math.random()						Get range in[0,1)Random values within

Random integer within the specified range:

function getRandom(min, max) {
  return Math.floor(Math.random() * (max - min + 1)) + min; 
}

2. Date object

Date object is different from Math object. Date is a constructor, so you need to instantiate it before you can use its specific methods and properties. The date instance is used to process date and time

  • To get the current time, you must instantiate:
var now = new Date();
Note: if no parameters are passed in when creating an instance, the date object obtained is the date object corresponding to the current time
  • Gets the date object for the specified time
var future = new Date('2022/5/1');
  • Some properties and methods of the Date instance
  • Get timestamp
// Instantiate Date object
var now = new Date();
// 1. Used to obtain the original value of the object
console.log(date.valueOf())	
console.log(date.getTime())	
// 2. Simple writing can do this
var now = + new Date();			
// 3. The method provided in HTML5 has compatibility problems
var now = Date.now();

3. Array object

(1) Create array

  • Literal mode
var arr = [1,"test",true];
  • new Array()
var arr = new Array();
Note: in the above code arr Create an empty array, if you need to use the constructor Array To create a non empty array, you can pass in parameters when creating the array
 The parameter transfer rules are as follows:
	If only one parameter is passed in, the parameter specifies the length of the array
	If more than one parameter is passed in, the parameter is called an element of the array

(2) Check whether it is an array

  • Instanceof operator: instanceof can determine whether an object is an instance of a constructor
var arr = [1, 23];
var obj = {};
console.log(arr instanceof Array); // true
console.log(obj instanceof Array); // false
  • Array.isArray(): Array. Isarray () is used to determine whether an object is an Array.isArray() is a method provided in HTML5
var arr = [1, 23];
var obj = {};
console.log(Array.isArray(arr));   // true
console.log(Array.isArray(obj));   // false

(3) Methods for adding and deleting array elements

(4) Array sorting

Note: the sort method needs to pass in parameters to set ascending and descending sorting

  • If "function (a, b) {return A-B;}" is passed in, In ascending order
  • If "function (a, b) {return B-A;}" is passed in, In descending order

(5) Get array index

(6) Convert array to string

Note: if the join method does not pass in parameters, the elements will be spliced according to ","

(6) Other methods


4. String object

(1) Basic package type

  • To facilitate the operation of basic data types, JavaScript also provides three special reference types: String, Number and Boolean.
  • The basic wrapper type is to wrap a simple data type into a complex data type, so that the basic data type has properties and methods
// What's wrong with the following code?
var str = 'andy';
console.log(str.length);

In principle, basic data types have no attributes and methods, while objects have attributes and methods, but the above code can be executed because js will package basic data types as complex data types. The execution process is as follows:

// 1. Generate temporary variables and wrap simple types into complex data types
var temp = new String('andy');
// 2. Assign a value to the character variable we declare
str = temp;
// 3. Destroy temporary variables
temp = null;

(2) String immutable

  • It means that the value inside is immutable. Although it seems that the content can be changed, in fact, the address has changed and a new memory space has been opened up in the memory.
  • When re assigning a value to a string variable, the previously saved string of the variable will not be modified. Re assigning a value to the string in memory will re open up space in memory. This feature is the immutability of the string. Due to the immutability of strings, there will be efficiency problems when splicing a large number of strings

(3) Returns the position according to the character

  • String through the basic wrapper type, you can call some methods to manipulate the string. The following is the method to return the position of the specified character

    Case: find the location and number of occurrences of all o in the string "abcoefoxyozopp"
Find the first one first o Location of occurrence
 Then just indexOf The result returned is not -1 Just keep looking back
 because indexOf Only the first one can be found, so the subsequent search uses the second parameter to add 1 to the current index to continue the search

(4) Returns characters based on position

String through the basic wrapper type, you can call some methods to operate the string. The following is the character at the specified position returned according to the position:


In the above methods, the charCodeAt method returns the ASCII code corresponding to the character at the specified position. The ASCII code comparison table is as follows:

Case: judge the character that appears most frequently in a string 'abcoefoxyozopp', and count its times

Core algorithm: Using charAt() Traverse this string
	Store each character to the object. If the object does not have this attribute, it will be 1. If it exists, it will be 1 +1
	Traverse the object to get the maximum value and the character
 Note: in the process of traversal, each character in the string is stored in the object as an attribute of the object, and the corresponding attribute value is the number of occurrences of the character

(5) Operation method of string

(6) replace method

character string.replace(The string to be replaced, the string to be replaced with);

(7) split method

The split() method is used to split strings, which can be split into arrays. After segmentation, a new array is returned

character string.split("Split character")

4, Simple and complex data types

1. Simple data type

Simple type (basic data type and value type): when storing, the value itself is stored in the variable, including string, number, boolean, undefined and null

2. Complex data type

Complex data type (reference type): when storing, only the address (Reference) is stored in the variable, and the objects (system objects, user-defined objects) created through the new keyword, such as Object, Array, Date, etc;

3. Heap, stack

  • Stack
    Stack (operating system): the operating system automatically allocates and releases the parameter values of stored functions and the values of local variables. Its operation mode is similar to the stack in the data structure;
    Simple data types are stored on the stack

  • heap
    Heap (operating system): it stores complex types (objects), which are generally allocated and released by the programmer. If the programmer does not release them, they are collected by the garbage collection mechanism.

  • Simple type storage
    The data of value type variables is stored directly in variables (stack space)

  • Storage of complex types
    Reference type variables (stack space) store addresses, and real object instances are stored in heap space

4. Simple type parameters

The formal parameter of a function can also be regarded as a variable. When we pass a value type variable as a parameter to the formal parameter of a function, we actually copy the value of the variable in the stack space to the formal parameter. Then any modification to the formal parameter inside the method will not affect the external variable.

function fn(a) {
    a++;
    console.log(a); 
}
var x = 10;
fn(x);
console.log(x);

Operation results

5. Complex data type parameters

The formal parameter of a function can also be regarded as a variable. When we pass a reference type variable to the formal parameter, we actually copy the heap address saved by the variable in the stack space to the formal parameter. The formal parameter and the actual parameter actually save the same heap address, so we operate on the same object.

function Person(name) {
    this.name = name;
}
function f1(x) { // x = p
    console.log(x.name); // 2. What is this output?    
    x.name = "Xue You Zhang";
    console.log(x.name); // 3. What is this output?    
}
var p = new Person("Lau Andy");
console.log(p.name);    // 1. What is this output?   
f1(p);
console.log(p.name);    // 4. What is this output? 

Operation results:

Non original, knowledge porter on the network.

Topics: Javascript Front-end