mrzappel

mrzappel

Frontend

1. HTML#

  1. Attribute differences. link is an XHTML tag, while @import is a syntax rule provided entirely by CSS.
    The link tag can do many other things besides loading CSS, such as the rel attribute preload, icon, etc., while @import can only load CSS.
  2. Differences in loading order. When a page is loaded (i.e., when it is being viewed by a user), the CSS referenced by link will be loaded simultaneously, while the CSS referenced by @import will wait until the entire page has been downloaded before being loaded. Therefore, sometimes when browsing a page that loads CSS via @import, styles may be missing at first (i.e., flickering), which is quite noticeable on slow networks.
  3. Differences in compatibility. Since @import was introduced in CSS 2.1, older browsers do not support it; @import can only be recognized in IE5 and above, while the link tag does not have this issue.
  4. Differences when using DOM to control styles. When using JavaScript to control the DOM to change styles, only the link tag can be used because @import cannot be controlled by the DOM.

2. CSS#

1. Double Flying Swallow Layout#

(1) Middle flex: 1

(2) HTML

<div class="content">
        <div class="content-left">left</div>
        <div class="content-middle">middle</div>
        <div class="content-right">right</div>
</div>

CSS

.content {
            display: flex;
        }
.content-left {
            flex: 0 0 200px;
            width: 200px;
            height: 200px;
            background-color: red;
        }
.content-middle {
            flex: 1;
            width: 100%;
            height: 200px;
            background-color: green;
            min-width: 700px;
        }
.content-right {
            flex: 0 0 200px;
            width: 200px;
            height: 200px;
            background-color: blue;
        }

Implementation effect:
Insert image description here
(3) Setting flex to 1
When flex takes a non-negative number, that number is the flex-grow value, flex-shrink takes 1, and flex-basis takes 0%. The following are equivalent:

.item {flex: 1;} .item { flex-grow: 1; flex-shrink: 1; flex-basis: 0%; } 

2. Standard Box Model and Quirky Box Model#

(1) Standard Box Model

Total length = width + padding (left and right) + border (left and right) + margin (left and right)

In the standard box model, when the width remains unchanged, changes in padding (left and right) and border (left and right) will change the total length.

(2) Quirky Box Model

Total length = width + margin (left and right)

In the total length of the quirky box model, when the size of width remains unchanged, changes in padding (left and right) and border (left and right) will only change within the width and will not change the total length.
(3)
When setting box-sizing: content-box, it is the standard mode, which is also the default mode;
When set to box-sizing: border-box, it is the quirky mode;

3. What are Sass and Less? What are the differences? Why do people use them?#

(1) sass-less
(2) Sass Documentation

3. JavaScript#

1. Differences and functions of return, break, and continue#

(1) The return keyword is not specifically used to break out of loops; the function of return is to end a method.
Unlike continue and break, return directly ends the entire method, regardless of how many layers of loops this return is within.
(2) The function of continue is somewhat similar to break, but the difference is that continue only interrupts the current loop and then starts the next loop. break, on the other hand, completely terminates the loop.
(3) break is used to completely end a loop and exit the loop body.

2. Detailed process from inputting URL to page display#

  1. User inputs URL to browser to retrieve data returned by the server
    First part:
    (1) Obtain the corresponding IP address of the website through DNS resolution
  2. First, check the local hosts file
  3. Send a DNS request to the local DNS server (query its cache records—recursive query)
  4. The local DNS server also needs to query the DNS root server (return the domain name server address—iterative process)
  5. The local DNS server sends a request to the domain name resolution server, at which point it can receive a correspondence between the domain name and IP address. The local DNS server not only needs to return the IP address to the user's computer but also needs to save this correspondence in the cache.
    (2) The browser and server perform a TCP three-way handshake.
  • First handshake: Client A sets the SYN flag to 1, randomly generates a value seq=J (where J ranges from 1234567) and sends a data packet to the server, Client A enters the SYN_SENT state, waiting for server B to confirm;
  • Second handshake: After receiving the data packet, server B knows that Client A requests to establish a connection by the SYN=1 flag. Server B sets both the SYN and ACK flags to 1, ack=J+1, randomly generates a value seq=K, and sends this data packet to Client A to confirm the connection request. Server B enters the SYN_RCVD state.
  • Third handshake: After Client A receives the confirmation, it checks whether ack is J+1 and ACK is 1. If correct, it sets the ACK flag to 1, ack=K+1, and sends this data packet to server B. Server B checks whether ack is K+1 and ACK is 1. If correct, the connection is successfully established, and Client A and server B enter the ESTABLISHED state, completing the three-way handshake. Subsequently, Client A and server B can start transmitting data.
    (3) The server's permanent redirect response, the browser follows the redirect address.
    (4) The server processes the request and returns a response.
  1. The browser retrieves data and renders it.
    (5) The browser retrieves data and renders it by constructing the DOM tree -> constructing the render tree -> laying out the render tree -> painting the render tree. This is well explained here: Detailed process from inputting URL to page display

3. TCP Four-Way Handshake#

(1)

  • First handshake: Client sends a FIN to close the data transmission from Client to Server, and Client enters FIN_WAIT_1 state.
  • Second handshake: After receiving FIN, Server sends an ACK to Client, confirming the sequence number as received number + 1 (similar to SYN, a FIN occupies a sequence number), and Server enters CLOSE_WAIT state.
  • Third handshake: Server sends a FIN to close the data transmission from Server to Client, and Server enters LAST_ACK state.
  • Fourth handshake: After Client receives FIN, it enters TIME_WAIT state, then sends an ACK to Server, confirming the sequence number as received number + 1, and Server enters CLOSED state, completing the four-way handshake.
    (2) Why is establishing a connection a three-way handshake while closing a connection is a four-way handshake? This is because when the server is in the LISTEN state and receives the SYN packet requesting to establish a connection, it sends both ACK and SYN in one packet to the client. However, when closing the connection, receiving the FIN packet from the other party only indicates that the other party will no longer send data but can still receive data. The local side may not have sent all data to the other party, so it can either close immediately or send some data to the other party before sending the FIN packet to indicate agreement to close the connection. Therefore, the ACK and FIN from the local side are generally sent separately.
    TCP Four-Way Handshake and Related
    TCP Fourth Handshake Why Wait 2MSL
    tcp Three-Way Handshake and Four-Way Handshake Details

4. Reflow and Repaint#

(1) Each element in the DOM node exists in the form of a box model, and the browser needs to calculate its position, size, etc. This process is called reflow; when the position, size, and other properties of the box model, such as color, font, etc., are determined, the browser begins to paint the content, and this process is called repaint.
(2) Causes of reflow: Adding or deleting visible DOM elements, changing element positions, changing element sizes—margin, padding, border, width, and height, changing content.
Causes of repaint: Color, background changes.
(3) Relationship: Reflow will definitely cause repaint, but repaint does not necessarily cause reflow.

5. Throttling and Debouncing#

(1) Debouncing
Execute once within 100 milliseconds after an event is triggered. If the event is triggered again within 100 milliseconds, the function execution time will be recalculated.
For example, real-time search when typing in a search box.
(2) Throttling
Refers to continuously triggering an event, executing the function only once within a certain period.
SMS verification code, can only be sent again after 60 seconds.

6. What are the ways to remove from the document flow?#

(1) Remove from document flow:
float
position: absolute
position: fixed
(2) How to restore document flow:
For floated elements, the parent element can use overflow: hidden
clear: both
(3) The position: relative property does not remove from the document flow, so the space occupied by the element will be retained.

7. Event Loop#

(1) JS browser event loop mechanism:
JavaScript events are divided into synchronous tasks and asynchronous tasks. When encountering synchronous tasks, they are placed in the execution stack for execution, while asynchronous tasks are placed in the task queue, waiting for the execution stack to finish before executing the events in the task queue.
(2) Node.js event loop
node.js event loop—overall structure
node.js event loop—auxiliary understanding
About node event loop in git
Before and after node11 (before, macro tasks after micro tasks; after 11, macro tasks executed after corresponding micro tasks)
The general execution order of tasks (macro tasks) is as follows:

timers: This phase executes the callbacks of setTimeout() and setInterval() that have been scheduled.
pending callbacks: Executes I/O callbacks that are deferred to the next loop iteration.
idle, prepare: For internal system use only.
poll: Retrieves new I/O events; executes callbacks related to I/O (in almost all cases, except for closed callbacks, which are scheduled by timers and setImmediate()), otherwise node will block here.
check: setImmediate() callback functions are executed here.
close callbacks: Some callbacks for preparing to close, such as: socket.on('close', ...).

(3) Macro tasks, micro tasks
Classification of macro tasks and micro tasks
Execution order examples
Macro tasks and micro tasks

8. Garbage Collection Mechanism#

(1) Garbage collection: When certain variables (such as local variables) are no longer involved in runtime, the system needs to reclaim the occupied memory space, which is called garbage collection.
(2) Memory leak: In some cases, the memory occupied by variables that are no longer used is not released in time, leading to an increase in memory usage during program execution, which can lead to system crashes or server downtime in extreme cases.
(3) Common garbage collection methods: Mark-and-sweep, reference counting.

  1. Reference counting: Records the number of times each value is referenced. When referenced, +1; when this value is referenced by another variable, -1. When this reference count becomes 0, the memory occupied by those values with a reference count of 0 will be released.
    Reference counting has a major problem: circular references.
    Solution: Manually break references (set to null manually).
  2. Mark-and-sweep
    When the garbage collector runs, it marks all variables stored in memory. Then, it removes the variables in the environment and those referenced by variables in the environment.
    The garbage collector completes the memory cleanup work, destroying those marked values and reclaiming the memory space they occupy.
    (4) How to reduce garbage collection in JavaScript?
    Try to reuse objects.
    Optimize loops; if function expressions in loops can be reused, it is best to place them outside the loop.
    (5) How to avoid memory leaks?
  3. Accidental global variables
    If bar is not declared, it will become a global variable and will not be released until the page is closed.
  4. Forgotten timers or callback functions
  5. Closures
    Define event handler functions externally to break closures.
  6. Uncleaned DOM element references
    Sometimes, saving internal data structures of DOM nodes is useful. If you want to quickly update a few rows of a table, it makes sense to store each row of DOM as a dictionary (JSON key-value pairs) or an array. At this point, the same DOM element has two references: one in the DOM tree and another in the dictionary. When you decide to delete these rows in the future, you need to clear both references.

9. Encapsulating JS into Plugins#

(1) My encapsulation
Circle drawing
Watermark background
(2) Encapsulation ideas and precautions
Encapsulation reference
Encapsulation reference
Personal ideas supplement:

  1. I generally start with procedural programming, and after implementing basic functionality, I transform it into object-oriented programming.
  2. Generally, there are several basic steps:
    ① Create a constructor function
    ② Change variables to properties
    ③ Change functions to prototype methods (some code that implements specific functionality can also be extracted into prototype methods)
    ④ Correct certain incorrect this references.

10. The difference between promise.catch and try catch#

(1) try/catch cannot catch the problem of promise.reject; the reason is that try catch cannot intercept asynchronous code.

function f2() {
  try {
    Promise.reject('An error occurred');
  } catch(e) {
    console.log(e)
  }
}
f2()   //Uncaught (in promise)

Solution:
(1.1) Use async await

async function f() {
  try {
    await Promise.reject('An error occurred')
  } catch(e) {
    console.log(e)
  }
}
f() // An error occurred

(1.2) promise.catch()

function f2() {
  try {
    Promise.reject('An error occurred').catch(err => {
      console.log('2', err)
    });
    console.log('1')
  } catch (e) {
    console.log(e)
  }
}
f2()

(1.3) The problem of try/catch cannot catch promise.reject
(2) Interception order
(2.1) After reject, the content will definitely enter the second callback in then; if there is no second callback written in then, it will enter catch.
(2.2) The content of resolve will definitely enter the first callback in then and will not enter catch.
(2.3) About the problem of reject and catch in promise

11. Data precision 0.001 + 0.002 != 0.003#

(1) Reason:
JS follows the IEEE 754 standard and uses double precision storage (double precision), occupying 64 bits;
It can be known that seemingly finite numbers, in the binary representation of computers, are infinite. Due to storage bit limitations, there is "truncation," and precision loss occurs.
(2) Solution:
(2.1) For low precision requirements
Math.floor rounds down.
Math.ceil rounds up.
Math.round rounds to the nearest.
toFixed() takes a certain number of decimal places.
(2.2) For simple calculations
Use multiplication to turn it into an integer, then use division to get the result.
Or encapsulate methods for calculations.
(2.3) Third-party libraries Math.js and big.js
Math.js
Official website
GitHub
Example

big.js
Official website
GitHub

12. Data persistence storage solutions (localstorage)#

localstorage
vuex
indexDB

13. Disadvantages of arrow functions#

(1) No prototype property
(1) Cannot use the new command
(2) Cannot use arguments
(3) Cannot be used as a generator function, cannot use the yield command

14. Differences between HTTP/1 and HTTP/2, and between HTTP and HTTPS#

Differences between HTTP/1 and HTTP/2, and between HTTP and HTTPS

15. Differences between promise and async/await#

Differences between promise and async/await

16. Common contents of ES6 (heihei summarizes quite comprehensively for supplementation)#

(1) Other ES6
Other ES6
(2) New basic data type Symbol in ES6
New basic data type Symbol in ES6

4. Vue#

1. Why is data a function instead of an object in Vue?#

If data were an object, multiple instances of the same component would operate on the same data property, leading to data confusion.
If it is a function, it returns independent, brand new data that will not affect each other (only functions {} form a scope).

2. Communication methods between Vue components#

  1. Props to pass data
    Applicable scenario: Parent component passes data to child component

  2. (emit triggers custom events)
    Applicable scenario: Child component passes data to parent component

  3. EventBus
    Usage scenario: Passing values between sibling components
    Sibling components trigger custom events through emit, where the second parameter of emit is the value being passed.
    Another sibling component listens for the custom event through $on.

  4. Vuex, state management tool

  5. Provide and inject
    Define the provide property in the ancestor component to return the value being passed.
    In descendant components, receive the value passed from the component through inject.

  6. PubSub.js
    // Publish message
    PubSub.publish('deleteTodo', index); // deleteTodo must match the subscription name, index is the specific data for communication
    PubSub.subscribe('deleteTodo', (msg, index) => {
    this.deleteTodo(index) // Call deleteTodo method to execute the actual business logic
    });

3. Observer pattern and subscription pattern: Differences and manifestations#

(1) The biggest difference between the observer pattern and the publish-subscribe pattern is that the publish-subscribe pattern has an event scheduling center.
(2) Insert image description here
(3) In the observer pattern, observers and targets interact directly, while in the publish-subscribe pattern, everything is handled uniformly by the scheduling center, allowing subscribers and publishers to be independent of each other. This not only achieves decoupling but also allows for finer-grained control. For example, if the publisher publishes many messages but does not want all subscribers to receive them, some processing can be done at the scheduling center, similar to permission control. Throttling operations can also be performed.
Observer pattern and subscription pattern

4. Two-way data binding (analyzing the relationship between observer, Dep, and watch)#

(1) Observer
Summary: The role of the Observer is to listen to the entire data. In the Observer class, the defineReactive method (which uses Object.defineProperty) hijacks the getter and setter of each property of the data.
Details: The Observer class mainly does the following:

  1. Binds a ob property to the data to store the Observer instance, avoiding duplicate bindings.
  2. If the data is an Object, it iterates through each property of the object to bind defineReactive.
  3. If the data is an Array, it needs to observe each member. Vue.js rewrites the seven methods of Array: push, pop, shift, unshift, splice, sort, reverse, to ensure that objects pushed/popped in later operations also have two-way binding. (See specific code in observer/array.js)
    (2) Dep
    Dep is a publisher. After dependency collection, Dep will have a subs array to store one or more observers, notifying all watchers when data changes.
    (3) Summary of (1) and (2)
    The relationship between Dep and Observer is that Observer listens to the entire data, iterates through each property of the data to bind the defineReactive method, fills dependencies into the Dep class during the getter (dep.depend), and notifies all watchers to update during the setter (dep.notify).
    (4) Watcher
    After receiving the notification, the watcher will update through the callback function.
    The watcher needs to achieve the following two functions:
  4. When dep.depend() is called, it adds itself to dep;
  5. When dep.notify() is called, it calls the watcher.update() method to update the view;
    Source code interpretation - the relationship among the three is easiest to understand*
    Auxiliary understanding 1
    Auxiliary understanding 2 - understanding from different angles

5. Diff Algorithm#

(1) Virtual DOM only compares elements at the same level.

(2) Vue first generates a virtual DOM based on the real DOM. When the data of a certain node in the virtual DOM changes, a new Vnode is generated, and then Vnode and oldVnode are compared. If differences are found, they are directly modified in the real DOM, and then the value of oldVnode is set to Vnode to achieve node updates.
(3) Brief principle
First compare at the same level, then compare child nodes.

First, determine if one side has child nodes while the other does not.

Compare the cases where both have child nodes.

Recursively compare child nodes.
(4) Principle diagram
Insert image description here
(5) Pointer comparison strategy
New front with old front
New back with old back
New back with old front (the node pointed to by the new front, moving the old back afterwards)
New front with old back (the node pointed to by the new front, moving the old front before)

(If not hit, change in the loop; if not in the loop, insert)
Diff algorithm

(6) Source code summary:

(1) Check if the two are the same element. If not, replace oldVnode with Vnode. patchVnode will compare these two nodes, determining whether Vnode and oldVnode point to the same object. If so, return directly and reuse the old real element. (2) If not, compare the new child node with the old byte. If both have text nodes and they are not equal, set the text node of el to the text node of Vnode; if both have child nodes, call updateChildren to compare their child nodes; if the current new node has no child nodes while the old node has child nodes, the old nodes will be deleted; if the current new node has child nodes while the old node has no child nodes, the new child nodes will be inserted into the old DOM.

(3) In the updateChildren method, four pairs of pointers are defined. First, compare whether the new and old first child nodes are the same. If they are, move the first two pointers forward. If the last new node has an extra child node, insert it into the old one. If the first child nodes are not the same, start comparing from the back (comparing from the tail child node). If the last one is found, insert the new node into the old DOM. Another situation is when both the head and tail nodes are not equal, compare the current head with the old tail node. If they are the same, move the old tail node to the front, then move the old tail pointer forward by one, and move the current head pointer to the next child node. Another way is to compare the old tail with the new head node. If they are the same, move the old tail to the front, then move the old tail pointer forward by one, and move the current head pointer to the next child node. If there is a key, the current child node's key will be used to find the old child node. If found, it will be moved to the front of the old node, and the pointer will be moved to the second child node of the current node, and so on. If the current child node is not found, it will be directly inserted into the old node, and finally, the extra child nodes in the old node will be deleted.

6. Vue's template parsing process and principles#

(1) Template parsing - quite comprehensive

(2) Template parsing - Supplement - General directive vs Event directive

(3) Detailed process of template parsing - parser, optimizer, code generator

(4) Detailed process of template parsing - parser, optimizer, code generator - Supplement 1

(5) Detailed process of template parsing - parser, optimizer, code generator - Supplement 2

(6) Detailed process of template parsing - parser, optimizer, code generator - Clear thinking

My thoughts (totaling the above):

  1. Parser

(1) The template string is thrown into the parseHTML function's while loop for iteration, segmenting until it is exhausted, resulting in an element AST.
(2) Start method (triggered whenever the start of a tag is parsed).
(3) End method (triggered whenever the end of a tag is parsed).
(4) Each time a segment of the tag's start is captured, it is pushed onto the stack; when the end of the tag is parsed, it is popped out. The stack is used to record a hierarchical relationship, tracking the depth of the DOM.
(5) Charts method (triggered whenever text is parsed).
(6) Comment method (executed when a comment is parsed).

  1. Optimizer
    (1) The goal of the optimizer is to identify static nodes and mark them.
    (2)
    Each time a re-render occurs, there is no need to create new nodes for static nodes;
    The patching process in the Virtual DOM can be skipped;
    (3) Main methods
    isStatic method (determines whether it is a static node)
    markStatic method (marks static nodes)
    markStaticRoots method (marks static root nodes)
  2. Code generator
    (1) Generates render function code strings.
    (2) Main methods
    genData processes the attributes of the current node on the AST, handling different attributes (e.g., attrs and props will call genProps for processing), and finally concatenates a string.
    genChildren generates the process of children, which is essentially a loop through the children of the current node in the AST.

7. Overall process of Vue#

Step 1: Parse the template into a render function.
Step 2: Reactive starts listening.
Step 3: Initial rendering, displaying the page, and binding dependencies.
Step 4: Data property changes, triggering re-render.

8. Setting up Vue scaffolding#

9. Returning to the list at the current position, and there won't be many DOM elements on the page.#

10. v-model passed to the child component, listening for changes.#

11. Differences between pseudo-classes and pseudo-elements.#

12. Implementation principle of $emit.#

13. Principle of Promise and handwritten implementation#

Most comprehensive promise 1
Most comprehensive promise 2
Introduction version of promise

14. Execution order of lifecycle methods in parent-child component nesting#

Parent beforeCreate ->
Parent created ->
Parent beforeMount ->
Child beforeCreate ->
Child created ->
Child beforeMount ->
Child mounted ->
Parent mounted

For solutions to corresponding issues, see the link
Execution order of parent-child components in Vue 1
Execution order of parent-child components in Vue 2

15. 1px pixel issue on mobile devices.#

16. Webpack packaging optimization and self-written loader.#

17. Differences and usage of rem, vh, vw.#

18. Macro tasks and micro tasks (what they are, differences).#

19. Front-end requests, contents in request headers.#

. CSS animations (examples).#

. How to make technical selections.#

Convenient

Technical strength.

20. Vue mixins#

(1) Mixins official documentation
(2) Mixins practical examples
(3) Points to note (priority):
Hook functions, methods, data objects, local mixins, global mixins.

5. React#

React interview questions

6. Mini Programs#

7. Webpack#

1. Webpack interview questions#

  1. Webpack interview summary
    Webpack – loader and plugin principles and differences
    Common Loaders in Webpack:
    css-loader: Loads CSS, supports modularization, compression, file import, etc.
    style-loader: Injects CSS code into JavaScript, loading CSS through DOM manipulation.
    file-loader: Outputs files to a folder, referenced in code via relative URLs.
    url-loader: Can inject file content into code as base64 if the file is small (8KB).
    image-loader: Loads and compresses image files.
    babel-loader: Converts ES6 to ES5.
    eslint-loader: Checks JavaScript code through ESLint.
    source-map-loader: Loads additional Source Map files for easier debugging.

Common Plugins
html-webpack-plugin generates HTML files.
Optimize CSS Assets Webpack Plugin is a Webpack plugin for optimizing/reducing CSS resources.
uglifyjs-webpack-plugin: Compresses JS.
commons-chunk-plugin: Extracts common code.
clean-webpack-plugin is used to delete previously built files before building, clearing duplicate files in dist.
HotModuleReplacementPlugin for hot updates.
define-plugin: Defines environment variables.
ProvidePlugin can automatically load modules anywhere without needing import or require methods.

  1. Differences between Loader and Plugin?
    (1) Different functions
    Loader translates to "loader." Webpack treats all files as modules, but it can only parse JS files natively. If you want to package other files, you will need to use loaders. Therefore, the function of a loader is to give Webpack the ability to load and parse non-JavaScript files.

Plugin translates to "plugin." Plugins can extend the functionality of Webpack, giving it more flexibility. During the lifecycle of Webpack, many events are broadcasted, and plugins can listen to these events and modify the output results at appropriate times using the APIs provided by Webpack.

(2) Different usages
Loaders are configured in module.rules, meaning they exist as parsing rules for modules. They are of type array, with each item being an Object describing what type of file (test) to use what loader and the parameters (options) used.

Plugins are configured separately in plugins. They are of type array, with each item being an instance of a plugin, and parameters are passed through the constructor.

  1. Webpack lifecycle (event nodes)

(1) Option initialization.

(2) Compile starts compiling.

(3) Make analyzes the entry file to create module objects.

(4) Build-module constructs modules.

(5) After-compile completes all module constructions, ending the compilation process.

(6) Emit, the compiler starts outputting generated assets, and plugins have the last chance to modify assets.

(7) After-emit output completes.

Specific process

  1. Code splitting in Webpack

Code splitting in Webpack

(1) Add a new entry to the entry field in the Webpack configuration file:
If the entry chunks contain duplicate modules, those duplicate modules will be introduced into each bundle.
This method is not flexible enough and cannot dynamically split core application logic.

For example, if both the index and another entry file contain the lodash module, then both split bundles will contain the lodash module, which is redundant. To solve this problem, the CommonsChunkPlugin plugin is needed.

(2) CommonsChunkPlugin
Separates business code from third-party module code.
(3) The import() syntax
Passing the path of the module, import() will return a Promise. This module will be treated as a split point, meaning this module and its submodules will be split into a separate chunk.

  1. Webpack packaging optimization

From both time and space perspectives
Perfect solution for Webpack packaging optimization

Space:
(1) CommonsChunk
Webpack recommends using CommonsChunk to package third-party libraries separately.
Disadvantage: Although CommonsChunk can reduce the size of the package, it has the problem that even if the code does not update, the vendor will be regenerated every time it is repackaged, which does not meet the original intention of separating third-party packages.
(2) Externals
Compared to the former, Webpack provides the method of Externals, which can introduce third-party libraries through external references: jquery.
It cannot solve the following problem:

import xxx from 'react/src/xx';

When Webpack encounters this problem, it will repackage the react code.
(3) DLL & DllReference
As long as the third-party library does not change, subsequent builds only need to package their business code, solving the problem of multiple references in Externals.

Time:

(4) Optimize loader configuration

4.1 Narrow the file matching range (include/exclude)
By excluding files under node_modules, the search range for loader loading is narrowed, increasing the probability of hitting files.
4.2 Cache the execution results of loaders (cacheDirectory)
cacheDirectory is a specific option for loaders, with a default value of false. The specified directory (use: 'babel-loader?cacheDirectory=cacheLoader') will be used to cache the execution results of loaders, reducing the need for Babel to recompile during Webpack builds. If set to an empty value (use: 'babel-loader?cacheDirectory') or true (use: 'babel-loader?cacheDirectory=true'), the default cache directory (node_modules/.cache/babel-loader) will be used. If the node_modules directory is not found in any root directory, it will fall back to the operating system's default temporary file directory.

(5) Resolve optimization configuration
5.1 Optimize module lookup paths resolve.modules
Webpack's resolve.modules configuration specifies where the module library (i.e., node_modules) is located. When writing import 'vue' in JS, which is neither a relative nor an absolute path, it will look for it in the node_modules directory. However, the default configuration uses an upward recursive search method, but typically there is only one node_modules in the project directory, located in the project root. To reduce the search range, the full path of node_modules can be specified directly; the same applies to alias (alias) configuration.
5.2 resolve.alias configures path aliases
5.3 resolve.extensions
When importing modules without file extensions, Webpack will automatically resolve the specified file extensions based on this configuration.
Export statements should include extensions as much as possible.

(6) module.noParse
Modules that use noParse will not be parsed by loaders, so when the libraries we use are too large and do not contain import require or define calls, we can use this configuration to improve performance by letting Webpack ignore the recursive parsing of files that do not adopt modularization.

(7) HappyPack
HappyPack allows Webpack to expand the execution process of loaders from a single process to a multi-process mode, meaning tasks are divided among multiple child processes for concurrent execution. After the child processes finish, the results are sent back to the main process, speeding up code construction. Using it in conjunction with DLL dynamic link libraries is even better.

(8) ParallelUglifyPlugin
This plugin can help projects with many entry points speed up build times by converting the serial compression of JS files into multiple child processes for parallel uglification.

(9) Tree Shaking
Removes unused code in JavaScript.

8. HTTP#

1. What is the difference between URL and URI?#

URI is a Uniform Resource Identifier, equivalent to a person's ID number.
Every resource available on the web, such as HTML documents, images, video clips, programs, etc., is located by a URI.
A URI generally consists of three parts:
① The hostname where the resource is stored.
② The naming mechanism for accessing the resource.
③ The name of the resource itself, represented by a path, emphasizing the resource.

URL is a Uniform Resource Locator, equivalent to a person's home address.
A URL is a string used on the Internet to describe information resources.
A URL generally consists of three parts:
① Protocol (or service method).
② The host IP address where the resource is stored (sometimes including the port number).
③ The specific address of the host resource, such as directory and file name.

9. Performance Optimization#

1. What threads are there in the browser's rendering process?#

(1) Concept:
Process: The basic unit of resource allocation in the system.
Thread: A thread is an entity within a process, independently scheduled and dispatched by the system.
Relationship: A process consists of one or more threads; multiple threads can collaborate to complete tasks; threads within the same process share the same memory space.
(2) Browser multi-process:
The browser's processes can be roughly divided into the following types:

  1. Browser main process (Browser process): Controls the Chrome address bar, bookmark bar, back and forward buttons, as well as the invisible parts of the browser, such as network requests and file access.
  2. Third-party plugin processes: Each plugin has a separate process, created only when the plugin is running.
  3. Browser rendering process (browser kernel, internally multi-threaded): Responsible for interface rendering, script execution, event handling, etc.
  4. GPU process: At most one, used for 3D rendering.
    (3) Browser rendering process (browser kernel)
    The browser kernel obtains page content, organizes information, calculates, and combines the final output visual image results, which is usually regarded as the browser rendering process. Chrome browser enables a separate process for each tab page, so each tab webpage has its own independent rendering engine instance. Some rendering processes may be merged by the browser's own optimization mechanism.
    (4) The browser kernel is multi-threaded.
  5. GUI thread
    Responsible for rendering the browser interface. GUI updates are stored in a queue and executed immediately when the JS engine is idle. This thread executes when the interface needs to be repainted or when a reflow is triggered by some operation.
  6. JS engine thread
    Also known as the JS kernel, responsible for processing JavaScript scripts. The JS engine always waits for tasks to arrive in the task queue and processes them. In a tab page, only one JS thread runs JS programs at any time.
  7. Timer trigger thread (whether multiple timer threads exist when there are multiple timers)
    The legendary setInterval and setTimeout threads, counting threads. The browser's timer counter is not counted by the JS engine.
  8. Event trigger thread
    Belongs to the browser rather than the JS engine. When the JS engine executes code blocks like setTimeout (which can also come from other threads in the browser kernel, such as mouse clicks, AJAX asynchronous requests, etc.), it adds the corresponding task to the event thread. When the corresponding event meets the trigger conditions, this thread adds the event to the end of the pending queue, waiting for the JS engine to process it.
  9. Asynchronous HTTP request thread
    XMLHttpRequest requests through a new thread opened by the browser after the connection. When a status update is detected, if no callback function is set, the asynchronous thread generates a state change event, placing this callback back into the event queue, waiting for the JS engine to execute it.
    Browser: What threads are there in the rendering process - comprehensive version
    Browser: What threads are there in the rendering process - supplementary version

2. Browser caching mechanism#

(1) Browser caching mechanism

When the browser accesses a resource that has been accessed before, it does the following:

  1. Check if it hits the strong cache; if it does, it directly uses the cache.

  2. If it does not hit the strong cache, it sends a request to the server to check if it hits the negotiated cache.

  3. If it hits the negotiated cache, the server will return 304 to tell the browser to use the local cache.

  4. Otherwise, it returns the latest resource.

Browser caching - strongest (theory + practice)

(2) Browser cache

  1. sessionStorage
    Advantages: Can store temporarily, automatically reclaimed when the page tab is closed, does not support cross-page interaction.
    Disadvantages: Can only be used as temporary storage, cannot store persistently.
  2. localStorage (storage size is generally 5M)
    Advantages: Used for long-term storage of the entire website's data, the stored data has no expiration time until manually deleted.
    Disadvantages: Size limitations, supported only in IE8 and above; currently, all browsers will limit the value type of localStorage to string type, which requires some conversion for common JSON object types.
  3. cookie (approximately 4KB can be stored in Google)
    Advantages: Best compatibility, almost all browsers support it.
    Disadvantages: Size limitations, and each time a request is sent, the cookie will be sent along with the request header. Currently, most login legitimacy verifications are done using cookies.
  4. userData
    Advantages: Emerged earlier than sessionStorage.
    Disadvantages: A storage method specifically for IE, with limited storage size. The size limit for a single file is 128KB, and a total of 1024KB can be saved under one domain name. The number of files should not be limited. In restricted sites, these two values are 64KB and 640KB, respectively.

3. Common design patterns#

  1. Singleton pattern: The constructor method is privatized, allowing only the class itself to create instances, while other classes cannot create instances.
    Advantages: In the singleton pattern, there is only one active instance of the singleton, and all instances instantiated from the singleton class are the same instance. This prevents other objects from instantiating it, ensuring that all objects access the same instance.
    Disadvantages: Not suitable for changing objects.
  2. Factory pattern: Establish a factory class to create instances of classes that implement the same interface.
    Advantages: Clarifies responsibilities and rights, benefiting the optimization of the entire software architecture.
    Disadvantages: Cannot freely add new classes, which would require changing the factory class.
  3. Proxy pattern: A class represents the functionality of another class.
    Advantages: Proxies the public interface.
    Disadvantages: Not all classes have interfaces; for classes that do not implement interfaces, dynamic proxies cannot be used.
  4. Observer pattern: Publish-Subscribe (Publish/Subscribe) pattern.
    Design patterns
    Supplement on design patterns

4. Process - Thread - Coroutine - Fiber#

  1. Process - the basic unit of resource allocation in the system.
  2. Thread - the basic unit of independent operation and scheduling.
  3. Coroutine - a lightweight thread in user mode; the scheduling of coroutines is entirely controlled by the application.
  4. Fiber - To help companies migrate their code to Windows faster and more accurately, Microsoft added fibers (Fiber) to the operating system; fibers are lighter-weight threads, and a thread can contain one or more fibers; fibers are implemented in user mode.
    Understanding the concepts of process, thread, coroutine, monitor, and fiber

10. Node#

Node interview questions 1
Node interview questions 3
Node interview questions 4
Not organized.

11. Algorithms#

12. Other Front-end#

  1. Webpack
  2. Axios

3. Front-end Cross-Domain (Mu)#

Cross-domain explanation
Summary:
If there is any inconsistency in the protocol, domain name, or port, it is cross-domain.
Solutions:
(1) document.domain + iframe cross-domain.
(2) JSONP Callback (the src attribute of the script tag is not constrained by the same-origin policy).
(3) CORS Cross-Origin Resource Sharing (Access-Control-Allow-Origin: *).
(4) Nginx reverse proxy.

# Nginx proxy server
server {
  listen       80;
  server_name  www.hahaha.com;
 
  location / {
    # Reverse proxy address
    proxy_pass   http://www.hahaha1.com:9999;  
    # Modify the domain name in the cookie
    proxy_cookie_domain www.hahaha1.com www.hahaha.com; 
    index  index.html index.htm;
		
    # Since the front-end cross-domain carries cookies, the Allow-Origin configuration cannot be *
    add_header Access-Control-Allow-Origin http://www.hahaha.com;  
    add_header Access-Control-Allow-Credentials true;
  }
}

4. Common Linux Commands (Mu)#

Common Linux commands and classifications
Linux commands - Beginner
Summary:
(1) ls -a
List all files in the directory.
(2) cd [directory name]
Switch the current directory to.
(3) pwd
View the current path.
(4) mkdir t
Create a folder named t in the current working directory.
(5) rmdir
Delete an empty directory.
(6) rm
-r recursively deletes, can delete subdirectories and files.
-f force deletes.
Delete files.
(7) mv
Move or rename.
(8) cp
Copy files.
(9) cat
View file content.
(10) tar
Used to compress and decompress files.
(11) ps -A
Display all current processes.
(12) kill
Kill a process.
(13) ping
Test network connectivity.

5. In the global scope, variables declared with const and let are not on window; where exactly are they? How to access them?#

Reference details
Summary:
(1) In ES6, global object properties and global variables are decoupled, but to maintain compatibility, the old remains unchanged. Therefore, global variables declared with var and function can still be seen on the window object, while global variables declared with let and const are not visible on the window object.
(2) In the global scope, global variables declared with let and const are not in the global object; they are just in a block scope (Script).
Insert image description here
(3) What are the differences between let, const, and var?
Reference 1
Reference 2

  1. var has variable hoisting; let and const do not have variable hoisting (var, let, const).
  2. Variables defined with var can be accessed across blocks but not across functions; let and const are only accessible within the current block (var, let, const).
  3. let and const cannot be redeclared (let, const).
  4. When const declares a primitive type (String, Number, boolean, null, undefined), the variable cannot change, and it must be initialized at declaration; otherwise, an error will occur. However, when declaring a reference type, only the address pointed to cannot change, and the variable can change.

6. The difference between computed and watch in Vue#

Computed properties:

  1. Supports caching; it will only be recalculated when dependent data changes.

  2. Does not support asynchronous operations; when there are asynchronous operations in computed, it is ineffective and cannot listen for data changes.

  3. If a property is calculated from other properties, this property depends on other properties, which is a many-to-one or one-to-one relationship, generally use computed.

  4. If the computed property is a function, it will default to use the get method; the return value of the function is the property value; in computed, properties have both a get and a set method, and when data changes, the set method is called.
    Watch properties:

  5. Does not support caching; when data changes, it directly triggers the corresponding operation.

  6. Watch supports asynchronous operations.

  7. The listener function receives two parameters; the first parameter is the latest value; the second parameter is the value before input.

  8. When a property changes, it needs to execute the corresponding operation; one-to-many relationship.

  9. The data being listened to must be declared in data or passed down from props in the parent component. When data changes, it triggers other operations; the function has two parameters,
    immediate: Immediately triggers the callback function execution when the component loads,
    deep: Deep listening, used to discover changes in internal values of objects, complex data types, such as changes in the contents of objects in an array. Note that listening for changes in arrays does not require this; only changes triggered in a reactive way will be listened to.

7. The two modes of vue-router (hash and history) and their differences#

Reference

  1. hash: # (essentially window.location.href); history (newly added in HTML).

  2. hash - For example, this URL: http://www.abc.com/#/hello, the hash value is #/hello. Its characteristic is that although the hash appears in the URL, it will not be included in the HTTP request, thus having no effect on the backend. Therefore, changing the hash will not reload the page; history - Utilizes the pushState() and replaceState() methods in the HTML5 History Interface.

  3. Calling history.pushState() has the following advantages compared to directly modifying the hash:
    1: The new URL set by pushState() can be any URL that is same-origin with the current URL; while hash can only modify the part after #, so it can only set URLs that are the same document as the current URL.
    2: The new URL set by pushState() can be exactly the same as the current URL, which will still add a record to the stack; while the new value set by hash must be different from the original to trigger an action to add a record to the stack.
    3: pushState() can add any type of data to the record through the stateObject parameter; while hash can only add short strings.
    4: pushState() can additionally set a title attribute for later use.

  4. There are the following disadvantages:
    1: In hash mode, only the content before the hash symbol will be included in the request, such as http://www.abc.com, so for the backend, even if routing is not fully covered, it will not return a 404 error.
    2: In history mode, the front-end URL must match the actual URL sent to the backend. For example, http://www.abc.com/book/id. If the backend lacks routing processing for /book/id, it will return a 404 error.

8. Differences between HTTP and HTTPS#

Reference

  1. The main differences between HTTPS and HTTP are as follows:

  2. The HTTPS protocol requires applying for a certificate from a CA, and generally, there are fewer free certificates, so it incurs some costs.

  3. HTTP is a hypertext transfer protocol, and information is transmitted in plaintext, while HTTPS is a secure SSL encrypted transmission protocol.

  4. HTTP and HTTPS use completely different connection methods and ports; the former uses port 80, while the latter uses port 443.

  5. The connection of HTTP is very simple and stateless; the HTTPS protocol is constructed by SSL + HTTP protocol, allowing for encrypted transmission and identity authentication, making it more secure than the HTTP protocol.

  6. When the client uses HTTPS to communicate with the web server, the following steps occur, as shown in the diagram.

(1) The client accesses the web server using the HTTPS URL, requesting to establish an SSL connection with the web server.

(2) After receiving the client's request, the web server sends a copy of the website's certificate information (which contains the public key) to the client.

(3) The client's browser negotiates the security level of the SSL connection with the web server, which is the level of information encryption.

(4) The client's browser establishes a session key based on the agreed security level and encrypts the session key using the website's public key, sending it to the website.

(5) The web server uses its private key to decrypt the session key.

(6) The web server uses the session key to encrypt communication with the client.

9. Summary of differences between pt, px, rem, and em#

Reference 1
Reference 2

  1. px (pixel)
    Pixels are the most basic points of data displayed on a screen, representing relative size (px displays differently at different resolutions).
  2. pt (point)
    A unit commonly used in the printing industry (pound), equal to 1/72 inch, representing absolute length.
  3. em
    Em is a relative length unit based on the font size of the parent element.
  4. rem
    Relative to the root element of HTML.
  5. Differences between rem and vw, vh.

10. How to hide certain middle digits of a phone number and replace them with asterisks; can you think of several methods?#

  1. Regular replacement
    phonenumber.replaceAll("(\d{3})\d{4}(\d{4})","$1****$2");
  2. String slicing and concatenation
    The substring() method is used to extract characters between two specified indices in a string.
    var str = '13812347829'; // This number is randomly generated; if there is any infringement, please contact the author for deletion!
    this.phoneNumber = str.substring(0,3)+'****'+str.substring(7,11);

11. What front-end image formats are there? What are the differences between these image formats? Which formats can set transparency, and which images can be displayed dynamically?#

Reference 1
Reference 2

  1. PNG
    Advantages:
    Transparent lossless compression;
    Progressive display and streaming read/write;
    Disadvantages:
    Limited color support (PNG8, PNG16, PNG32);
    IE6 does not support PNG24 transparency effects.
  2. JPEG (jpg)
    Does not support transparency,
    Does not support animation,
    Interlaced progressive display,
    JPEG is the most suitable for web photography images.
  3. GIF
    Transparency,
    Supports animation,
    Lossless,
    Interlaced progressive display,
  4. SVG
    Easy to modify and edit,
    SVG graphic format can be used to dynamically generate graphics (can dynamically generate interactive maps using SVG, embed them in web pages, and display them to end users).
    Vector graphics, smaller file sizes, and can provide high-definition images, suitable for direct printing or output.

12. How to display SVG images#

  1. Using the tag's src
    At this point: Most browsers will not load files referenced by SVG itself (other images, external scripts, font files, etc.).

  2. Use Object or iframe to import SVG images

<object type="image/svg+xml" data="example.svg" class="example">
 My Example SVG
</object>

<iframe src="example.svg" class="example"></iframe>

When SVG files are introduced as application objects, their sizes are similar to those introduced as references and will not inherit any styles defined in the parent document.
However, unlike the previous method, this method can contain external files, and scripts can communicate between the object and the parent document.

  1. Using inline SVG
<!DOCTYPE html>
<html>
  <body>
    <svg>
      ...
    </svg>
  </body>
</html>

Directly embedded SVG will inherit the styles of the parent document and will be displayed in inline mode by default.

Links: https://www.cnblogs.com/sese/p/8669746.html
https://segmentfault.com/a/1190000004447771

13. Event delegation and event delegation#

  1. Example: Receiving a package
    (1) Three people are waiting for a package at the company entrance; (2) Delegating to the front desk to sign for it.
    (2) An old employee can receive it, and a new employee can also receive it.

  2. Event delegation is achieved by utilizing the bubbling principle of events, where events start from the deepest node and gradually propagate upwards;
    For example, to add click events to each li in a ul, you only need to delegate the event to the parent element ul;
    There is no need to bind click events to each li;
    When an li is clicked, due to the bubbling principle, the event will bubble up to the ul, and since there is a click event on the ul, the event will be triggered;
    All li elements and dynamically added li elements will achieve delegation.

  3. There are three phases: 1. Event capturing phase, 2. Event target phase, 3. Event bubbling phase.

    1. The number of managed functions is reduced. 2. It is convenient to dynamically add and modify elements without needing to modify event bindings due to element changes. 3. The association between JavaScript and DOM nodes is reduced, thus decreasing the probability of memory leaks caused by circular references.

14. Differences between reference types and basic data types#

  1. (1) Common basic data types in JS include undefined, null, number, boolean, string;
    (2) The reference data types in JS are object types, such as Object, array, function, data, etc.;
    (3)
    var num = 10; // value type, value is on the stack
    var obj = {}; // complex type, object is on the heap, address (reference) is on the stack
  2. Data type judgment
    (1) typeof
    For basic types, except for null (returns object), it can return correct results.
    For reference types, except for function, it returns object type.
    For function, it returns function type.
    (2) instanceof
    instanceof is generally used to check arrays.
    [] instanceof Object; // true
    [] instanceof Array; // true
    So there are drawbacks.
    (3) Object.prototype.toString can accurately determine the type.

15. Differences between front-end call, apply, and bind#

  1. call(), apply(), and bind() are all used to change the this reference.
  2. (1) Invocation: bind returns a new function that needs to be called to execute.
    call and apply do not return a new function; they are called directly.
    (2) Parameters
    obj.myFun.call(db, 'Chengdu', 'Shanghai'); // Demar, age 99, from Chengdu to Shanghai
    obj.myFun.apply(db, ['Chengdu', 'Shanghai']); // Demar, age 99, from Chengdu to Shanghai
    obj.myFun.bind(db, 'Chengdu', 'Shanghai')(); // Demar, age 99, from Chengdu to Shanghai

apply's second parameter is an array.

16. How to swap variables without using a third variable#

  1. Arithmetic operations
a = a + b;
b = a - b; // b = (a + b) - b, i.e., b = a
a = a - b; // a = (a + b) - a
  1. Bitwise operations (XOR)
    a = a ^ b;
    b = a ^ b; // b = (a ^ b) ^ b, i.e., b = a;
    a = a ^ b; // a = (a ^ b) ^ a.

17. What is keep-alive, how to use it, and is there a limit to the number of caches?#

  1. Function: Cache components to avoid re-rendering.
  2. Usage:
    (1) include - String or regular expression. Only components with matching names will be cached.
    exclude - String or regular expression. Any components with matching names will not be cached.
    max - Number. The maximum number of component instances that can be cached.
<keep-alive include="home">
 <router-view></router-view>
</keep-alive>

(2) Add fields in the routing to dynamically judge at keep-alive.
3. If cached components want to clear data or execute initialization methods, call the activated hook function when loading the component, as follows:

activated: function () {
  this.data = ''
}

18. export and export default#

  1. To allow external access to a variable inside a module, the export keyword must be used to output that variable.
  2. export allows multiple exports and can be used multiple times; when importing, use curly braces to import as needed.
  3. export default allows a single anonymous export; when importing, it can be named arbitrarily.
19. Calculate the factorial of a number using recursion#
def f(x):
    if x >= 1:
        return x * f(x - 1)   # Calls itself, 6 is okay
    else:
        return 1    # Prevents entering an infinite loop
a = int(input("Please enter a number: "))
print(f(a))

Output:
Please enter a number: 5
120

Process finished with exit code 0

19. Spread operator#

  1. Extracts each item that can be iterated over and copies it into the current object.
  2. Usage:
    (1) Arrays (spread operator)
    1.1 Destructuring assignment
    If the spread operator is used for array assignment, it can only be placed at the last position of the parameters; otherwise, it will throw an error.
const [first, ...rest] = [1, 2, 3, 4, 5];
first // 1
rest // [2, 3, 4, 5]
const [first, ...rest] = [];
first // undefined
rest // [];
const [first, ...rest] = ["foo"];
first // "foo"
rest // [];

1.2 Copying arrays
1.3 Merging arrays

(2) Objects
The spread operator (...) is used to extract all traversable properties of the parameter object and then copy them into the current object.

let person = {name: "Amy", age: 15};
let someone1 = {name: "Mike", age: 17, ...person};
console.log(someone1);  // {name: "Amy", age: 15}

(3) Functions
Functions with an uncertain number of parameters.

20. Deep and shallow copy#

Deep and shallow copies are both regarding reference data types;
A shallow copy only copies the reference of the object, so changes to the copied object will also change the original object. Only a deep copy is a true copy of the object.

Common shallow copy methods:
concat(),
slice(),
Object.assign(),
spread operator.

Deep copy:
JSON.stringify/parse (disadvantage: undefined, any function, and symbol values will be ignored during serialization).
Recursively traverse, determine data types, and assign values until it reaches the basic data type.

21. Mutating arrays#

Triggers the reactivity of arrays.
push()
pop()
shift()
unshift()
splice()
sort()
reverse()

22. Prototype && Prototype Chain#

When trying to get a property of an object, if this object does not have this property, it will look for it in the 'prototype' property of its constructor. Since the 'prototype' property is an object, it also has a 'proto' property.
Insert image description here

23. Implementation of inheritance#

  1. Prototype chain inheritance
    The proto of the subclass points to an instance of the parent class.
    Disadvantages: First, it cannot achieve multiple inheritance; second, all properties from the prototype object are shared among all instances, and when creating a subclass instance, it cannot pass parameters to the parent class constructor. To add properties and methods to the subclass, it must be executed after Student.prototype = new Person().
function father(phone, sex) {
    this.phone = phone;
    this.sex = sex;
    this.say = function() {
        console.log("This is your father's method");
    }
}
function son(name, age) {
    this.name = name;
    this.age = age;
    this.eat = function() {
        console.log("Eating");
    }
}
son.prototype = new father("110", "Female");
var tomCat = new son("tomcat", 15);
  1. Constructor inheritance
    The subclass internally calls the parent class method and uses call to change its scope to point to the subclass's this, thus bringing the parent class's method over.
    Disadvantages: Its instance is not an instance of the parent class, and it can only inherit the properties of the parent class, not those on the parent class's prototype, and cannot achieve function reuse.
function father2(phone, sex) {
    this.phone = phone;
    this.sex = sex;
    this.say = function() {
        console.log("This is your father's method");
    }
}
function son2(name, age) {
    father2.call(this, "120", "Male");
    this.name = name;
    this.age = age;
    this.eat = function() {
        console.log("Eating");
    }
}
var jerui = new son2("tomcat", 15);
console.log(jerui);
  1. Combination inheritance of prototype chain + constructor
    Inherits properties through the constructor and methods through the prototype.
    Disadvantages: The parent class constructor is called twice, creating two instances.
  2. Optimized combination inheritance
    By pointing the parent class prototype and subclass prototype to the same object, the subclass can inherit the public methods of the parent class as its own public methods without initializing instances twice, avoiding the disadvantages of combination inheritance.
  3. Class inheritance in ES6
    Class can achieve inheritance through the extends keyword and can define static methods of the class through the static keyword.
    The essence of ES5 inheritance is to first create the subclass's instance object this, and then add the parent class's methods to this (Parent.apply(this)). The essence of ES6 inheritance is completely different; it first adds the properties and methods of the parent class instance object to this (so the super method must be called first), and then modifies this using the subclass's constructor.
    It should be noted that the class keyword is just syntactic sugar for prototypes; JavaScript inheritance is still based on prototypes.

24. Scope && Scope Chain#

  1. In JavaScript, the scope is divided into global scope and function scope.
    Global scope:
    Code can be accessed anywhere in the program; built-in properties of the window object have global scope.

Function scope:
Can only be accessed in a fixed code

Loading...
Ownership of this post data is guaranteed by blockchain and smart contracts to the creator alone.