js basic problems

JS
1.this pointing problem
this points to a deeper understanding of the address
(1) Function call, this points to its caller

function foo() { 
    console.log(this.bar); 
} 
var bar = "bar1"; 
var o2 = {bar: "bar2", foo: foo}; 
var o3 = {bar: "bar3", foo: foo}; 

foo();   //   bar1      
o2.foo();  //     bar2     
foo.call(o3);  //  bar3

(2)

var name = 'Nicolas';
function Person(){
    this.name = 'Smiley';
    this.sayName=function(){
        console.log(this); 
        console.log(this.name); 
    };
    setTimeout(this.sayName, 0);     // Second output
}

var person = new Person();
person.sayName();		// First output

Output Person, Smiley for the first time
Output window for the second time, Nicolas. Although setTimeout is defined in the constructor, it is called in window when it is called.
(3)

function Person() {
  this.name = "Smiley";
  this.sayName = function(){
    console.log(this);
    console.log(this.name); 
  };
}

let person = new Person();
person.sayName.call({name: "Nicolas"});

Output {name: "Nicolas"} and "Nicolas"
Call changes the direction of this. The content in call is this

(4)

function Person() {
  this.name = "Smiley";
  this.sayName = function(){
    console.log(this);
    console.log(this.name); 
  };
}

let person = new Person();
// Note that there are no parentheses after sayName, so the sayName method is not called
let sayNameCopy = person.sayName;
sayNameCopy();

Output window and undefined
Change the invocation method and do not call directly: use the assignment to make the call. At this point, this points to window.
(5)

function Person() {
  this.name = "Smiley";
  this.sayName = ()=> {
    console.log(this);
    console.log(this.name); 
  };
}

let person = new Person();
person.sayName.call({name: "Nicolas"});

Output Person and "Smiley"
This is because the arrow function does not have its own this. Where it is defined, this points to who, and the priority is higher than the explicit call, and the direction of this cannot be changed. If there is no caller, the arrow function points to Windows
2. What is the difference between the title and alt attributes of img tags
alt: alternate text displayed on the web page when the picture fails to load
title: the text displayed when the mouse (the attribute on the mobile phone is meaningless) is placed on the picture
Lazy loading of pictures
Principle: a picture is a label. Whether the browser requests a picture is based on the src attribute of < img >, so the key to lazy loading is not to assign a value to the src of < img > when the picture does not enter the visual area, so that the browser will not send a request, and assign a value to the src when the picture enters the visual area.
realization:
1. loading pictures
2. Determine which pictures to load [ key ]
3. Loading pictures invisibly
4. Replace true picture
Steps:
The height of the document display area of the innerHeight window does not include the menu bar
scrollTop the height the mouse rolls over
offsetTop height from the top of the browser
Innerheight + scrolltop > offsettop start loading
3. What are the ways of inheritance?
4.reduce
Explain in detail
prev: return value of the last function call
cur: current element
Index: current element index
arr: traversed array
let arr = [1, 2, 3, 4];
let sum = arr.reduce(function(prev, cur, index, arr) {
return prev + cur;
},5)
The first number is 5. Start with 5 and add 5 + 1 + 2 + 3 + 4

let names = ['Alice', 'Bob', 'Tiff', 'Bruce', 'Alice'];

let nameNum = names.reduce((pre,cur)=>{
  if(cur in pre){
  //Object, with brackets
    pre[cur]++
  }else{
    pre[cur] = 1 
  }
  return pre
},{})
console.log(nameNum); //{Alice: 2, Bob: 1, Tiff: 1, Bruce: 1}

5. Calculate the depth of the array

const arr=[[2,[2,6]],2]
let tem=[]
function deep(arr){
  for (let i = 0; i < arr.length; i++) {
    if (arr[i] instanceof Array) { // Determine whether it is an array
      deep(arr[i])
    }else{
      tem.push(arr[i])
    }
  }
  return tem
}
console.log(deep(arr))//[2,2,6,2]

6.[].concat.apply array flattening

const arr = [1,2,[3,4,5,[6,7],8],9,10,[11,[12,13]]];

const flatten = (arr) => {
while (arr.some(item => Array.isArray(item))){
arr = [].concat.apply([], arr);
}
return arr;
}

apply changes the direction of this and splices the arr into []
apply (this, [arr1,arrr2,arr3]) transfers parameters in this way. Its second parameter is an array, so it obviously conforms to our previous topic setting, so [[12,21], [1,2,3], [2,3,4]] = > [arr1,arrr2,arr3], Arr1 = > [12,21]; arr2=>[1,2,3]; arr3=>[2,3,4]; apply will pass the parameters in turn, and then use concat to connect these separate arrays into an array. New array element subscripts start at 0.
7. Common Plugin
html-webpack-plugin

Generate html files. Insert the css style extracted from the relevant entry chunk and extract text webpack plugin configured in the webpack into the template or templateContent configuration item provided by the plug-in, and generate an html file based on the content specified in the templateContent configuration item. The specific insertion method is to insert the style link into the head element and the script into the head or body.

const HtmlWebpackPlugin = require('html-webpack-plugin')

plugins: [
  new HtmlWebpackPlugin({
    filename: 'index.html',
    template: path.join(__dirname, '/index.html'),
    minify: {
      // Compress HTML file
      removeComments: true, // Remove comments from HTML
      collapseWhitespace: true, // Delete whitespace and newline
      minifyCSS: true, // Compress inline css
    },
    inject: true,
  }),
]

inject has four option values

true: Default value, script Label at html Document body bottom
body: script Label at html Document body Bottom (same as) true)
head: script Label at head Inside label
false: Do not insert generated js File, just simply generate one html file

clean-webpack-plugin

Clean webpack plugin is used to clean up the bundle file generated by the last project before packaging. It will be based on output Path automatically cleans up folders; This plug-in is frequently used in the production environment, because the production environment often generates many bundle files through hash. If it is not cleaned, it will generate new files every time, resulting in a very large folder.

const { CleanWebpackPlugin } = require('clean-webpack-plugin')

plugins: [
  new HtmlWebpackPlugin({
    template: path.join(__dirname, '/index.html'),
  }),
  new CleanWebpackPlugin(), // Name of the folder to be cleaned
]

extract-text-webpack-plugin

Generate css files instead of inline. The main purpose of this plug-in is to separate css styles and prevent page style loading disorder caused by packaging styles in js

const ExtractTextPlugin = require('extract-text-webpack-plugin')

lugins: [
  // Separate the CSS into the index. In the CSS folder under the / dist folder css
  new ExtractTextPlugin('css/index.css'),
]

8. Front end optimization
(1) Sprite diagram to prevent multiple loading of pictures
(2) Put CSS in the HEAD. If you put CSS in other places, such as BODY, the browser may have started rendering the page before downloading and parsing to CSS, which leads to the page jumping from no CSS state to CSS state, and the user experience is poor. In addition, some browsers will not render the page until the CSS download is completed. If the CSS is placed in the lower position, the browser will delay the rendering time.
(3) Reduce scope chain lookup and declare local scope
(4) Event delegation
In fact, event delegation is to delegate the response events (click, keydown...) that need to be bound to the child element to the parent element by using the JS event bubbling mechanism, so that the parent element can play the role of event listening. The principle of event broker is event bubbling of DOM elements.
advantage:

  1. Greatly reduce memory consumption and event registration.
  2. The new element implements dynamic binding events
    (5) Rolling event, anti shake throttling
    (6) Using HTTP2
    HTTP2 compared to http1 1 has the following advantages:
    Fast parsing speed
    The server parses http1 1, bytes must be read in continuously until the delimiter CRLF is encountered.
    The request to parse HTTP2 is not so troublesome, because HTTP2 is a frame based protocol, and each frame has a field representing the frame length.
    Multiplexing
    HTTP1. If you want to initiate multiple requests at the same time, you have to establish multiple TCP connections, because a TCP connection can only process one http1 at the same time 1.
    On HTTP 2, multiple requests can share a TCP connection, which is called multiplexing. The same request and response shall be represented by a flow and identified by a unique flow ID.
    Multiple requests and responses can be sent out of order in a TCP connection, and then reconstituted through the flow ID after reaching the destination.
    Header compression
    HTTP 2 provides header compression.
    If you can store the same header and send only the different parts between them, you can save a lot of traffic and speed up the request time.
    HTTP/2 uses the "header table" on the client and server to track and store previously sent key value pairs. For the same data, it is no longer sent through each request and response.
    priority
    HTTP 2 can set a higher priority for more urgent requests. After receiving such requests, the server can give priority to processing.
    flow control
    Because the traffic bandwidth of a TCP connection (depending on the network bandwidth from the client to the server) is fixed, when multiple requests are concurrent, one request accounts for more traffic and the other request accounts for less traffic. Flow control can accurately control the flow of different flows.
    Front end optimization specific
    (7) Lazy loading of pictures
    const img = document.querySelector('img')
    img.src = img.dataset.src
    Place the img tag's data souce at the real address of the picture

Keywords: Javascript Front-end TypeScript

Added by Txtlocal on Mon, 24 Jan 2022 01:31:36 +0200