Js data type

Basic data types: Number String Boolean Null Undefined Symbol and ES2020 BigInt reference types: Array Object Function Math Date etc

Js type judgment

  1. Typeof returns undefined string Boolean number symbol Bigint function Object.
typeof NaN // 'number'
Copy the code
  1. Instanceof detects reference types, as well as multiple layers of inheritance.
  2. Constructor is unsafe because the direction of constructor can be changed. Null and undefined do not have this method.
  3. Object. The prototype. ToString. Call () returns a value of ‘[Object] capitalize the first letter of the data type’.

Ps: the above you can see typeof can accurately judge the basic types, but the typeof null will return to the object, the object. The prototype. ToString. Call () accurately identified any data type. PS: All object keys are stored as strings, even if you don’t have a given string type key. Object cannot be used to call keys that begin with a number. A comparison of objects is a comparison of their respective references.

Js type conversion

The object.prototype.valueof () method returns the original valueof the specified Object. If the Object has no original value, valueof returns the Object itself. This method is called automatically during a type conversion.

object The return value
Array Returns the array object itself
Boolean Boolean value
Date The time stamp
Function The function itself
Number A numeric value
Object By default, the object itself is returned
String A string value

Object. The prototype. The toString () method returns a string said Object. This method is also called automatically during a type conversion.

Transformation rules

ValueOf is called first when a non-base type is converted, and toString is called if valueOf cannot return a valueOf the base type

Strings and Numbers

  • The + operator, if either of them is a string, is converted to string concatenation
  • – operator to a number for calculation
[] + {} // "[object Object]"
{} + [] / / 0
Copy the code

Boolean and number

1 + true  / / 2
1 + false / / 1
Copy the code

All logical judgments are converted to Booleans

This correlation

  • This is the environment object in which the code is currently executing and always points to an object in non-strict mode, which can be any value.
  • In the global execution environment this refers to the global object.
  • Inside a function, the value of this depends on how the function is called.
  • This cannot be assigned during the execution of a function, and its value may vary each time the function is called.

Change the action this points to:

  • Call is called immediately, with a single second argument
  • Apply is called immediately, and the second argument is an array
  • Bind does not call immediately, returns a new function, and binds this permanently. (This cannot be changed once you bind this.)
  • Arrow functions (arrow functions do not have their own this and inherit this from the upper level of scope)
  • New When a function is used as a constructor, its this is bound to the new object being constructed.

PS: new takes precedence over bind

The prototype

Each instance object has a private __proto__ attribute that points to its constructor’s prototype object.

Prototype chain

If the prototype is not found, the Object will continue to search for the prototype Object until it finds the prototype of object. prototype. At this point, the prototype is null and the search stops. This upward chain of lookups through prototype links is called a prototype chain.

Inheritance of the prototype chain

When a new object is created, the __proto__ of the newly created object is directed to the prototype object of its constructor. This mechanism is called inheritance of the prototype chain. Methods are defined on stereotypes and properties are defined on constructors.

An object can use properties or methods of another object. This is called inheritance. Specifically, the prototype of this object is set to another object. In this way, according to the rules of the prototype chain, if the attribute of one object is searched when it does not exist, another object will be searched, which means that an object can use the attribute and method of another object.

Closure, scope

Closures are functions that have access to variables in the scope of another function. The essence of closures is that there are references to parent scopes in the current environment.

The whole execution process of JS code is divided into two stages: compilation stage and execution stage. The compilation phase is done by the compiler, translating code into executable code, where scoping rules are determined. The execution phase is done by the engine, mainly executing executable code, and the execution context is created in this phase.

We define scopes as a set of rules that govern how the engine performs variable lookups based on identifier names in the current scope and nested subscopes.

When we access a variable, the compiler executes the code by looking for the identifier in the current scope. If it doesn’t find it, it looks in the parent scope. If it doesn’t find it, it looks up until it reaches the global scope. A chain formed in this search process is called the scope chain.

Js loop mechanism

Js is single threaded. Tasks in JS are divided into synchronous tasks and asynchronous tasks

  • Synchronization task: a task that is queued to be executed on the main thread can be executed only after the previous task is completed.
  • Asynchronous task: does not enter the main thread, but entersTask queueThe task. onlyTask queueNotify the main thread that an asynchronous task is ready to execute, and the task will be executed on the main thread.
  • Asynchronous tasks in the task queue can be executed only after all synchronous tasks of the main thread are executed.
  • Task queue is divided into macro task queue and micro task queue.
  • Macro tasks include: setTimeout setInterval setImmediate(node only) requestAnimationFrame(browser only) UIrendering(browser only) I/O
  • Microtasks include: Process. nextTick, MutationObserver, Promise.then Catch Finally

The PS: New Promise operation is synchronous. Serving:

function fn(){
    console.log(1);
    
    setTimeout(() = > {
        console.log(2);
        Promise.resolve().then(() = > {
            console.log(3);
        });
    },0);
    
    new Promise((resolve, reject) = > {
        console.log(4);
        resolve(5);
    }).then(data= > {
        console.log(data);
    });
    
    setTimeout(() = > {
        console.log(6);
    },0);
    
    console.log(7);
}
fn(); 
 
[console.log(1), new Promise(), console.log(7)]; Macrotask: [setTimeout1, setTimeout2] MicroTask: [promise2. Then] The output is 1, 4, 7 2. Until all synchronization tasks are completed, the call stack is emptied; Stack: []; macrotask: [setTimeout1, setTimeout2] microtask: [promise2.then] 3. Push the microtask onto the stack, execute stack: [promise2. Then]; Macrotask: [setTimeout1, setTimeout2] MicroTask: [] Output 4. At this point, the microtask queue is empty, so the macro task starts to execute, and pushes setTimeout1 in the macro task queue to the execution stack. Stack: [setTimeout1]; Macrotask: [] MacroTask: [] MacroTask: [] MacroTask: [] MacroTask: [] MicroTask: [] MacroTask: [] MacroTask: [] MacroTask: [] MicroTask: [] MacroTask: [] [setTimeout2] microtask: [promise1.then] 5. Then] MacroTask: [setTimeout2] MicroTask: [] Output: 3 6. Stack: [setTimeout2] MacroTask: [] MicroTask: [] Finally, the stack and the task queue are empty, and the code is finished. The final output order is: 1 4 7 5 2 3 6 perfect!! * * /
Copy the code

Promise

Promise is a constructor that generates a Promise instance. Simply put, a Promise is a container that holds some event that will end in the future (usually the result of an asynchronous operation)

  • The state of the Promise object is unaffected by the outside world – it can only go from pedding to fullied alive
  • Once the state changes, it never changes again, and you can get this result at any time
  • Unable to cancel Promise
  • If the callback function is not set, errors thrown inside a Promise will not be reflected externally.
  • When in pedding state, it is impossible to know the current progress stage (just started or about to be completed).

To be continued…