1. Understand Event Loop
- JavaScript is a single line. (Reason :JavaScript’s primary purpose is to interact with users and manipulate the DOM, which makes it single-threaded.)
- All synchronization tasks are executed on the main thread, forming an execution stack.
- In addition to the main thread, there is a “task queue” (message queue). Whenever an asynchronous task has a result, an event is placed in the “task queue”.
- Once all synchronization tasks in the execution stack are completed, the system reads the task queue to see what events are in it. Those corresponding asynchronous tasks then end the wait state, enter the execution stack, and start executing.
- The main thread repeats the fourth step above.
Summary: The main thread reads events from the “task queue” in a continuous Loop, so the whole operation mechanism is also called the Event Loop.
More on the Event Loop
2. Scope and scope chain
- Scope:
- Scope in Javascript is about accessibility and visibility of variables. That is, what parts of the program have access to the variable, or where the variable is visible.
- Javascript uses lexical scope (static scope), which means that the role of a variable is determined at compile time (scope at definition time).
- Global scope: Any variable not declared in a function or braces is in global scope. Variables declared in global scope can be accessed anywhere in the program
- Function scope: If a variable is declared inside a function, it is under a function scope. These variables can only be accessed inside the function, not outside it.
- Block-level scope: Variables declared in curly braces using let and const exist in block-level scope. These variables cannot be accessed outside of braces.
- Scope chain:
- A scope chain is used to find variables. A scope chain is a series of scopes connected together. When a variable is used in Javascript, the Javascript engine first tries to find the variable in the current scope, if not, then in its upper scope, and so on until the variable is found or in the global scope. If the variable is still not found in the global scope, it either implicitly declares the variable in the global scope (in non-strict mode) or reports an error directly.
- Variables are searched from inside out
- Inner variables can mask outer variables of the same name
Reference: clear javascript scope
Reference: Understand Javascript scopes and scope chains
3. The closure
function foo() {
let a = 2
function too() {
console.log(a)
}
return too
}
foo()() // 2
Copy the code
When a function executes, it returns another executable function, which retains access to the outer function scope in which it was defined. Foo ()() executes foo, then too. “Too” is defined in scope foo, but “too” is defined in scope foo, taking the nearest nested property, a = 2, according to scope chain rules.
Advantages:
- Used to save private attributes: Attributes and functions that do not need to be exposed are stored in the parent function of the closure to avoid interference with values by external operations
- Avoid namespace clutter caused by local attributes contaminating the global variable space
Disadvantages:
- Because closures cause variables in a function to be stored in memory, which can be very memory consuming, you should not abuse closures because they can cause performance problems on your web page
Conclusion: A closure is a function that can read variables inside other functions. Closures are understood as functions defined inside functions.
4. This point
- Normally this points to
- Pure function calls. (This is the most common use of a function and is a global call, so this stands for global object.)
- A call as an object method. (A function can also be called as a method on an object, in which case this refers to the parent object.)
- Called as a constructor. A constructor is a function that generates a new object. In this case, this refers to the new object.
- How do I change the direction of this
- Use the arrow function of ES6. Arrow function this always refers to this when the function is defined, not when it is executed. If the arrow function is contained by a non-arrow function, then this is bound to the nearest non-arrow function’s this; otherwise, this is undefined.
- Use _this = this inside the function
- Use apply, call, and bind
- Apply and Call are basically similar, except that they take different arguments (the call method takes a list of arguments, whereas Apply takes an array of arguments).
- Bind creates a new function that must be called manually (the bind method takes a list of arguments).
- This.X is not the same as the scope variable. This is not in the current environment, so it will not look up
Summary: This is the environment object in which the function is run. (This always refers to the object that called it last)
Reference: This usage of Javascript
Reference: JavaScript’s This principle
References: this, apply, call, bind
5. The MVC and MVVM
- MVC (M: model V: view C: controller)
Features: The communication between the parts is as follows, all communication is one-way.
- The View sends instructions to the Controller
- After the Controller completes the business logic, it asks the Model to change state
- The Model sends the new data to the View, and the user gets feedback
graph TD
View --> Controller --> Model --> View
Conclusion: The business logic of MVC mode mainly focuses on Controller, while the front View actually has the ability to independently process user events. When each event flows through Controller, this layer will become very bloated. In addition, View and Controller are generally one-to-one in MVC, which represent a component together. The too close connection between View and Controller makes the reusability of Controller a problem.
- MVVM(M: Data layer V: View VM: bridge between View and Model)
graph TD
ViewModel-->View --> ViewModel -->Model -->ViewModel
Under the framework of MVVM, View and Model cannot communicate directly. They communicate through the ViewModel. The ViewModel usually implements an observer, and when the data changes, the ViewModel can listen for changes in the data and notify the corresponding view for automatic updates. And when the user manipulates the view, the ViewModel can also listen for changes in the view. It then notifies the data that it has changed, effectively enabling two-way binding of the data. And views and ViewModels in MVVM can communicate with each other.
- contrast
MVVM not only simplifies business and interface dependencies, but also eliminates frequent data updates (frequent DOM operations), reduces application coupling, and improves code reuse
Reference: A brief introduction to MVC and MVVM models
6. Vue2 principle
1._init: initializes the lifecycle, events, props, methods, data, computed, and watch. The most important of these is setting setters and getters via Object.defineProperty for “reactive” and “dependent collection”
2.compile:
- Parse: The template template is used to parse instructions, class, and style data to form an AST.
- Optimize: marks static nodes,
patch
Diff algorithm will directly skip the static node, thus reducing the process of comparison, optimizationpatch
Performance. - Generate: Process of converting an AST into a render function string (the render string (vnode node))
3. Patch: core Diff algorithm, which compares tree nodes of the same layer instead of searching and traversing the tree layer by layer.
4. Data changes
-
setter
-
dep.notify()
-
watcher.update()
-
QueueWatcher (this) // Watcher passes itself into queueWatcher() in the queueWatcher method
-
Queue.push (watcher) queue.push(watcher) queue.push(watcher) queue.push(watcher) queue.push(watcher) queue.push(watcher)
-
! waiting && waiting = true && nextTick(() => { // … Execute run} for all watcher’s in queue (so when changing a value, call dom directly to get the latest one, only when the tick completes)
-
waiting= false
Conclusion: Data hijacking combined with published-subscribe mode is adopted. Set and GET of each attribute is hijacked by object.defineProperty () method, and messages are published to subscribers when data changes, triggering corresponding listener callback. Data changes update views, and views change update data.
Reference: Analyze the internal operation mechanism of vue.js
7. Prototypes and prototype chains
-
Reference types, which have object properties and can extend properties freely.
-
Each reference type has an implicit prototype __proto__ attribute whose value is an ordinary object.
-
The reference type, the implicit prototype __proto__ property value points to the explicit prototype property value of its constructor.
-
When you try to get a property of an object, if the object doesn’t have the property itself, it will look in its implicit prototype __proto__ (that is, the explicit prototype of its constructor).
Conclusion: The concept of prototype chain: the instance first reviews itself from itself and finds that there is notoString
Methods. If you can’t find it, go up and look for the prototype property of the constructor. The constructor’s prototype is also an Object, and that Object’s constructor is Object, so we found the toString method under Object.prototype. This search process is called the prototype chain
Reference: You need to understand prototypes and prototype chains