preface

Just half a month into the job, joined the new company seamlessly, perfect. I took time to sort out the interview questions I met recently. The interview companies included: Ali, Tencent, Midea, SF express and Ping an Financial Service. Base is shenzhen, the last three have got the offer smoothly, there is still a little gap from dachang, come on duck ~ because it is the primary front-end, the interview questions may be too basic, please point out the error ๐Ÿ˜„. Some questions are not very comprehensive answer on the spot, follow-up online information supplement, there may be a lot of similarities, ha ha, there are a lot of questions can be seen on this website, strong push wave: HTTPS://muyiy.cn/question/
Copy the code

1. Introduce BFC and its application

- BFC is Block Formatting Context (Block-level Formatting Context). It is a CSS rendering mode in the page box layout. It is equivalent to an independent container, and the elements in it and the external elements do not affect each other. - The BFC can be created using an HTML root elementfloatFloat position (absolute, fixed) Overflow values other than visible (hidden, auto, scroll) display are inline-block, table-cells, flexCopy the code

Landing the features

1) Margins will fold under the same BFC.

The following example shows that the two boxes are only 100px apart. This is not a CSS bug, but can be interpreted as a specification. If you want to avoid overlapping margins, you can put them in different BFC containers.

<head>
    <style>
        div{
            width: 100px;
            height: 100px;
            margin: 100px;
            border: 1px solid red;
        }
    </style>
</head>
<body>
    <div></div>
    <div></div>
</body>
Copy the code

I can change it to something like this

<head>
    <style>
        p{
            width: 100px;
            height: 100px;
            margin: 100px;
            border: 1px solid red;
        }
        div{
            overflow: hidden;
        }
    </style>
</head>
<body>
    <div>
        <p></p>
    </div>
    <div>
        <p></p>
    </div>
</body>
Copy the code

2) BFC can contain floating elements (clear floating)

<head>
    <style>
        p{
            width: 100px;
            height: 100px;
            background: black;
            float: left;
        }
        div{
            width: 100%;
            border: 1px solid red;
            /* Clears floating divs that can contain floating elements */
            overflow: hidden;
        }
    </style>
</head>
<body>
    <div>
        <p></p>
    </div>
</body>
Copy the code

3) BFC prevents elements from being overwritten by floating elements

Here is a text wrap effect

<head>
    <style>
        div{
            width: 100px;
            height: 100px;
            background: #4CAF50;
            float: left;
        }
        section{
            width: 300px;
            border: 1px solid red;
            margin: 100px;
        }
    </style>
</head>
<body>
    <section>
        <div>I float on the left</div>
        <p>This is a piece of text. BFC stands for Block Formatting Context. It is a CSS rendering mode in the layout of the page box model.</p>
    </section>
</body>
Copy the code

Add overflow: Hidden to the p element

p{
    overflow: hidden;
}
Copy the code

This method can be used to implement a two-column adaptive layout with a fixed width on the left and an adaptive width on the right

2. How to judge arrays? Please introduce their differences and advantages and disadvantages respectively

Object. Prototype. ToString. Call (),instanceof,ArrayIsArray () as welltypeof
Copy the code

1) the Object. The prototype. ToString. Call ()

Every Object that inherits Object has a toString method, which, if not overridden, returns [Object type], where type is the type of the Object. However, when toString is used directly on objects other than Object, it returns a string of contents, so we need to use call or apply to change the execution context of toString.

const an = ['Hello'.'World'];
an.toString(); // "Hello,World"
Object.prototype.toString.call(an); // "[object Array]"
Copy the code

This method evaluates all basic data types, even null and undefined. However, custom object types cannot be distinguished. You can use Instanceof to distinguish custom object types

console.log(Object.prototype.toString.call("this"));//[object String]
console.log(Object.prototype.toString.call(12));//[object Number]
console.log(Object.prototype.toString.call(true));//[object Boolean]
console.log(Object.prototype.toString.call(undefined));//[object Undefined]
console.log(Object.prototype.toString.call(null));//[object Null]
console.log(Object.prototype.toString.call({name: "this"}));//[object Object]
console.log(Object.prototype.toString.call(function(){}));//[object Function]
console.log(Object.prototype.toString.call([]));//[object Array]
console.log(Object.prototype.toString.call(new Date));//[object Date]
console.log(Object.prototype.toString.call(/\d/));//[object RegExp]
function Person(){};
console.log(Object.prototype.toString.call(new Person));//[object Object]
Copy the code

Object. The prototype. ToString. Call () is often used to judge the built-in browser Object.

2) instanceof

Instanceof’s internal mechanism is to determine whether the prototype of the type can be found in the prototype chain of the object.

Use instanceof to determine whether an object is an Array. Instanceof checks whether the object’s archetype is found in the Array’s archetype chain, returning true if it is found, false otherwise.

However, instanceof can only be used to determine object types, not primitive types. And all Object types instanceof Object are true.

instanceof Array; // true
instanceof Object; // true
'a' instanceof String; //false
Copy the code

3) Array. IsArray ()

  • Function: Used to determine whether an object is an array
  • Instanceof with isArray

Array.isArray is superior to instanceof when detecting Array instances because array. isArray can detect iframes

var iframe = document.createElement('iframe');
document.body.appendChild(iframe);
xArray = window.frames[window.frames.length- 1].Array;
var arr = new xArray(1.2.3); / / [1, 2, 3]

// Correctly checking for Array
Array.isArray(arr);  // true
Object.prototype.toString.call(arr); // true
// Considered harmful, because doesn't work though iframes
arr instanceof Array; // false
Copy the code
  • Array. IsArray () and the Object. The prototype. ToString, call () Array. The isArray () is a method that ES5 additional when there is no Array. The isArray (), You can use the Object. The prototype. ToString. Call () implementation.
if (!Array.isArray) {
    Array.isArray = function(arg) {
        return Object.prototype.toString.call(arg) === '[object Array]';
    };
}
Copy the code

4) typeof

typeofOnly basic data types can be detected, including Boolean,undefinedString, number, symbol, andnull,Array,Object, the use oftypeofAll of them tested positiveObjectCannot detect the specific reference type.Copy the code

How do I center a div horizontally and vertically

<div class="parent">
    <div class="child"></div>
</div>
Copy the code

1) Position + Transform is used when the width height is variable

.parent{
    position: relative;
}
.child{
    position: absolute;
    left: 50%;
    top: 50%;
    transform: translate(50%, 50%); }Copy the code

2) Position + Transform is used with width and height

.parent{
    position: relative;
}
.child{
    width: 100px;
    height: 100px;
    position: absolute;
    left: 50%;
    top: 50%;
    margin-left: -50px;
    margin-top: -50px;
}
Copy the code

3) Use Flex

.parent{
    display: flex;
    align-items: center;
    justify-content: center;
}
Copy the code

or

.parent{
    display: flex;
    align-items: center;
}
.child{
    margin: 0 auto;
}
Copy the code

or

.parent{
    display: flex;
}
.child{
    margin: auto;
}
Copy the code

4) Use position

.parent{
    position: relative;
}
.child{
    position: absolute;
    left: 0;
    top: 0;
    right: 0;
    bottom: 0;
    margin: auto;
}
Copy the code

5) Use grid

.parent{
    display: grid;
}
.child{
    justify-self: center;
    align-self: center;
}
Copy the code

6) Use table

.parent{
    display: table;
}
.child{
    display: table-cell;
    vertical-align: middle;
    text-align: center;
}
Copy the code

or

.parent {
    display: table-cell;
    text-align: center;
    vertical-align: middle;
}
.child {
    display: inline-block;
}
Copy the code

7) Use pseudo classes

.parent{
    font-size: 0;
    text-align: center;
}
.parent::before {
    content: "";
    display: inline-block;
    width: 0;
    height: 100%;
    vertical-align: middle;
}
.child{
    display: inline-block;
    vertical-align: middle;
}
Copy the code

4. What does the following code print and why?

var b = 10;
(function b(){
    b = 20;
    console.log(b); }) ();Copy the code

In normal mode:

var b = 10;
(function b() {
   // The internal scope is set to 20 if there is a declaration of the existing variable b. Function b(){} function b(){}
   // The IIFE function cannot be assigned (internal mechanism, like const const), so it is invalid.
  // The internal mechanism of IIFE in JS engine, stack storage of IIFE, etc.
    b = 20;
    console.log(b); // [Function b]
    console.log(window.b); // 10, not 20}) ();Copy the code

Error reported in strict mode:

var b = 10;
(function b() {
  'use strict'
  b = 20;
  console.log(b)
})() // "Uncaught TypeError: Assignment to constant variable."
Copy the code

There are window:

var b = 10;
(function b() {
    window.b = 20; 
    console.log(b); // [Function b]
    console.log(window.b); // 20 is inevitable}) ();Copy the code

Var:

var b = 10;
(function b() {
    var b = 20; // IIFE internal variables
    console.log(b); / / 20
   console.log(window.b); / / 10}) ();Copy the code

5. What does the following code print and why?

var a = 10;
(function () {
    console.log(a)
    a = 5
    console.log(window.a)
    var a = 20;
    console.log(a)
})()
Copy the code

Say the first

The sequence is undefined, 10,20

var a = 10;
(function () {
    // Redefines a in the function, variable promotion, preparsing
    console.log(a);//undefined
    a = 5;
    console.log(window.a);// a is a function local variable
    var a = 20;
    console.log(a);/ / 20, of course}) ()console.log(a);//10, equivalent to window.a
Copy the code

Replace it with this:

var a = 10;
(function () {
    // There is no redefinition in the function
    console.log(a);/ / 10
    a = 5;
    console.log(window.a);/ / 5
    a = 20;
    console.log(a);/ / 20, of course}) ()console.log(a);//20, equivalent to window.a
Copy the code

Replace it with this:

var a = 10;
function b() {
    // Redefines a in the function, variable promotion, preparsing
    console.log(a);//undefined
    a = 5;
    console.log(window.a);// a is a function local variable
    var a = 20;
    console.log(a);/ / 20, of course
}
b();
console.log(a);//10, equivalent to window.a
Copy the code

6. Repaint & Reflow and how to optimize

Let’s take a look at the browser rendering process

From the image above, we can see that the browser renders as follows:

1, parse HTML, generate DOM Tree, parse CSS, generate CSSOM Tree 2, combine DOM Tree and CSSOM Tree, generate Render Tree 3, Layout(backflow): according to the generated Render Tree, backflow (Layout), get node geometry information (location, 5. Display: Send pixels to GPU for Display on the page. (There is a lot more to this step, such as merging multiple compositing layers into a single layer on the GPU and displaying them on a page, while cSS3 hardware acceleration works by creating a new compositing layer.)Copy the code

The rendering process looks pretty simple, so let’s look at what we did at each step.

Generate render tree

To build the render tree, the browser does the following:

  1. Each visible node is traversed starting at the root of the DOM tree.
  2. For each visible node, find the corresponding rules in the CSSOM tree and apply them.
  3. The render tree is composed from each visible node and its corresponding style.

So in the first step, since we talked about traversing the visible nodes, we need to know what nodes are not visible. Invisible nodes include:

  • Nodes that do not render output, such as script, meta, link, etc.
  • Some nodes are hidden by CSS. Such as display: none. Note that nodes hidden with opacity and opacity will still be displayed in the rendering tree. Only nodes with display: None are not displayed in the rendering tree.

Note: The render tree contains only visible nodes

backflow

By constructing the render tree, we combine the visible DOM nodes with their corresponding styles, but we also need to calculate their exact position and size in the device viewport. This stage of calculation is called backflow.

To figure out the exact size and location of each object on the site, the browser traverses from the root of the render tree, which can be represented in the following example:


      
<html>
    <head>
        <meta name="viewport" content="width=device-width,initial-scale=1">
        <title>Critial Path: Hello world!</title>
    </head>
    <body>
        <div style="width: 50%">
        <div style="width: 50%">Hello world!</div>
        </div>
    </body>
</html>
Copy the code

You can see that the first div sets the display size of the node to 50% of the viewport width, and the second div sets its size to 50% of the parent node. In the backflow phase, we need to convert the viewport to the actual pixel value depending on the width of the viewport.

redraw

Finally, we know which nodes are visible, the style of the visible nodes and the specific geometric information (location, size) by constructing the render tree and the backflow phase, so we can convert each node of the render tree into an actual pixel on the screen. This phase is called the redraw node.

Now that we know how the browser renders, let’s talk about when backflow redraws occur.

When reflux redraw occurs

As we have already seen, the backflow phase mainly computs the location and geometry of nodes, so when the page layout and geometry information changes, backflow is needed. For example:

  • Add or remove visible DOM elements
  • The position of the element changes
  • The size of the element changes (including margins, inner borders, border size, height, width, etc.)
  • Content changes, such as text changes or an image being replaced by another image of a different size.
  • When the page is first rendered (which is inevitable)
  • Browser window size changes (because backflow calculates element position and size based on viewport size)

Note: Backflow must trigger redraw, and redraw does not necessarily backflow

Depending on the extent and extent of the change, large or small portions of the rendering tree need to be recalculated. Some changes can trigger a rearrangement of the entire page, such as when a scrollbar appears or when a root node is modified.

Browser optimization mechanisms

Modern browsers are smart enough to optimize the redraw process by queuing changes and executing them in batches, since each redraw incurs additional computational overhead. The browser queues changes until a certain amount of time has passed or a threshold has been reached. But! Queue refresh is forced when you retrieve layout information from operations, such as when you access the following properties or use the following methods:

  • OffsetTop, offsetLeft, offsetWidth, offsetHeight
  • ScrollTop, scrollLeft, scrollWidth, scrollHeight
  • ClientTop, clientLeft, clientWidth, clientHeight
  • getComputedStyle()
  • getBoundingClientRect
  • Specific can access the site: gist.github.com/paulirish/5…

All of the above attributes and methods need to return the latest layout information, so the browser has to clear the queue and trigger a backflow redraw to return the correct value. Therefore, it is best to avoid using the attributes listed above when modifying styles, as they all refresh the render queue. If you want to use them, it is best to cache the values.

Reduce backflow and redraw

All right, now for the big story of the day, with all this background and theory, let’s talk about how to reduce backflow and redraw.

Minimize redraw and rearrange

Since redrawing and rearranging can be expensive, it is best to reduce the number of times it occurs. To reduce the number of occurrences, we can merge the DOM and style changes multiple times and then dispose of them all at once. Consider this example

const el = document.getElementById('test');
el.style.padding = '5px';
el.style.borderLeft = '1px';
el.style.borderRight = '2px';
Copy the code

In the example, there are three style attributes that have been modified, each of which affects the element geometry and causes backflow. Of course, most modern browsers are optimized for this, so that only one rearrangement is triggered. However, if the layout information (which triggers backflow above) is accessed by other code in an older browser or while the above code is executing, this will result in three rearrangements.

Therefore, we can merge all the changes and deal with them in sequence. For example, we can do the following:

  • Using cssText
    const el = document.getElementById('test');
    el.style.cssText += 'border-left: 1px; border-right: 2px; padding: 5px; ';
    Copy the code
  • Modify the CSS class
    const el = document.getElementById('test');
    el.className += ' active';
    Copy the code

Specific reference: muyiy.cn/question/br…

7. Align the ends of the text

<div>The name</div>
<div>Mobile phone number</div>
<div>account</div>
<div>password</div>
Copy the code
div {
    margin: 10px 0; 
    width: 100px;
    border: 1px solid red;
    text-align: justify;
    text-align-last: justify;
}
Copy the code

8, [‘1’, ‘2’, ‘3’]. Map (parseInt)

First the results: ['1'NaN, NaN. Why not ['1'.'2'.'3'Here's the analysisCopy the code
  • The map() method returns a new array whose elements are the values processed by the call to the original array element.

  • The map() method processes the elements in their original array order.

Map (parseInt)

map(function(item, index){
    return parseInt(item, index);
})
Copy the code

That is, the sequence runs as follows:

parseInt('1'.0);
parseInt('2'.1);
parseInt('3'.2);
Copy the code

The use of the parseInt

  • The parseInt(String, radix) function parses a string and returns an integer.
  • When the radix parameter is 0 or not set, parseInt() determines the cardinality of the number based on string.
  • Radix is optional. Represents the radix of the number to be parsed. The value is between 2 and 36.

So: parseInt(‘1′, 0); //’1’ parseInt(‘2’, 1); //NaN parseInt(‘3’, 2); //NaN, since there is no 3 in base 2

9. Write the print result of the following code

function changeObjProperty(o) {
    o.siteUrl = "http://www.baidu.com";
    o = new Object(a); o.siteUrl ="http://www.google.com";
} 
let webSite = new Object(a); changeObjProperty(webSite);console.log(webSite.siteUrl);
Copy the code

This problem zha see small problem, in fact hidden mystery. Answer first:

console.log(webSite.siteUrl); //"http://www.baidu.com"
Copy the code

The final report is as follows:

function changeObjProperty(o) {
    Var o = webSite; var o = webSite; Assignment changes the properties of an object
    o.siteUrl = "http://www.baidu.com";
    // the variable o refers to the new address and changes after the old address have nothing to do with it
    o = new Object(a); o.siteUrl ="http://www.google.com";
}
Copy the code

Change the title to the following:

function changeObjProperty(o) {
    o.siteUrl = "http://www.baidu.com";
    o = new Object(a); o.siteUrl ="http://www.google.com";
    return o;
} 
let webSite = new Object(a); changeObjProperty(webSite);console.log(webSite.siteUrl);
let newSite = changeObjProperty(webSite);
console.log(newSite.siteUrl);
Copy the code

The output is as follows:

console.log(webSite.siteUrl); //"http://www.baidu.com" console.log(newSite.siteUrl); //"http://www.google.com"Copy the code

10, array deduplication

var arr = [2.0.1.9.1.0.2.1];
Copy the code
  • indexOf
var arr = [2.0.1.9.1.0.2.1];
var a_arr = [];
for(let i=0; i<arr.length; i++){if(a_arr.indexOf(arr[i]) == - 1){ a_arr.push(arr[i]); }}console.log(a_arr);
Copy the code
  • Two for loops
var arr = [2.0.1.9.1.0.2.1.4];
var a_arr = [];
for(let i=0; i<arr.length; i++){var flag = true;
    for(let j=0; j<a_arr.length; j++){if(arr[i] == arr[j]){
            flag = false; }}if(flag){ a_arr.push(arr[i]); }}console.log(a_arr);
Copy the code
  • ES6 set method
var arr = [2.0.1.9.1.0.2.1.4];
var a_arr = [...new Set(arr)]
console.log(a_arr);
Copy the code
  • The filter method
var arr = [2.0.1.9.1.0.2.1.4];
function unique(array) {
    var res = array.filter(function(item, index, array){
        return array.indexOf(item) === index;
    })
    return res;
}
console.log(unique(arr));
Copy the code

11. What happens when a page is loaded from the input URL to the display?

1, the browser will start a thread to process the request, analyze the URL to determine if it is HTTP protocol according to the Web processing;2Call the corresponding method in the browser kernel, such as loadUrl method in WebView;3Obtain the IP address of the URL through DNS resolution, set the UA and other information to send the second GET request;4, HTTP protocol session, the client sends a header (request header);5. Access the Web Server on the Web Server, such as Apache, Tomcat, and Node.js.6Enter the deployed back-end applications, such as PHP, Java, JavaScript, Python, etc., to find the corresponding request processing;7If the browser has accessed it and there is a corresponding resource in the cache, it will be compared with the last modification time of the server and returned if the time is consistent304;
8The browser starts downloading the HTML document (response header, status code)200), while using caching;9, document tree establishment, according to the mark request required to specify the MIME type of the file (such as CSS, JS), and set the cookie;10, the page starts rendering DOM, JS operates DOM according to DOM API, performs event binding, etc., and the page display is complete.Copy the code

12. Ajax implementation principle and method use

AJAX is not a JavaScript specification; it comes from an acronym: Asynchronous JavaScript and XML, which means Asynchronous network requests performed in JavaScript.Copy the code

Native Ajax request steps

// Create an XMLHttpRequest object
var ajax = new XMLHttpRequest();
// Specify the type of request, URL, and whether the request is processed asynchronously.
ajax.open('GET',url,true);
// Type of content encoding when sending messages to the server
ajax.setRequestHeader("Content-type"."application/x-www-form-urlencoded"); 
// Send the request
ajax.send(null);  
// Accept server response data
ajax.onreadystatechange = function () {
    if (obj.readyState == 4 && (obj.status == 200 || obj.status == 304)) {}};Copy the code

13. Talk about the principle of key in VUE

It is convenient for the update of diFF algorithm, and the uniqueness of key enables the algorithm to find the DOM that needs to be updated more quickly. It should be noted that the key should be unique, otherwise there will be very hidden update problems.Copy the code

14. What is the principle of VUE bidirectional binding?

Two-way data binding redefines get and based on Object.defineProperty()setMethod. Modify the triggersetMethod, gets the value of the trigger GET method, and publishes information through data hijacking.Copy the code
let obj = {
    name: 't-one'.location: {x: 100.y: 200}}function render(){
    console.log('Render view');
}

function observe(data){
    for(let key indata){ defineData(data, key, data[key]); }}function defineData(data, key, value){
    Object.defineProperty(data, key, {
        get(){
            return value;
        },
        set(newValue){
            render();
            value = newValue;
        }
    })
}
observe(obj);
obj.name = 'liu';
console.log(obj.name);//liu
Copy the code

A simple two-way binding

<input type="text" id="input"> <div id="content"></div> <script> function obersver(data){ for(let i in data){ defineData(data,i,data[i]); } } function defineData(data,key,value){ Object.defineProperty(data,key,{ get:function(){ return value; }, set: function(newValue){console.log(' set===='); value = newValue; document.getElementById('content').innerHTML = newValue; } }) } let obj = {}; document.addEventListener('keyup',function(e){ obersver(obj); obj.text = e.target.value; console.log(obj.text); }) </script>Copy the code

What is the function of $nextTick in VUE?

Deal with the problem that the DOM is not updated in time after dynamic data changes. $nextTick gets the latest DOM changes after the data is updatedCopy the code

Talk about front-end engineering, modular, componentization

Front-end engineering

1Analyze, organize and build front-end projects as a system engineering to achieve clear project structure, clear division of labor, tacit team cooperation and improved development efficiency2Engineering thinking is the separation of structure, style and action. Such as directory is divided into assets, the components, the router, utilCopy the code

Front-end modularization

1Modularization and componentization can be simply considered as the expression form of engineering2There are many AMD/CommonJS/UMD/ES6 modules,CSS modular development is mostly in less, SASS, stylusCopy the code

Es6 brings a modular approach to language native:

const methodOne = params= > {
    console.log(params)
}
const methodTwo = params= > {
    console.log(params)
}
// Export method 1
export default {
    methodOne,
    methodTwo
}
// Export method 2
export {
    methodOne,
    methodTwo
}
Copy the code
Import mode 1 corresponds to export mode 1
import module from './module'
module.methodOne();

Import mode 2 corresponds to export mode 2
import { methodOne } from './module'
methodOne();
Copy the code

Front end componentization

1Componentization the page is regarded as a container, each independent part of the page such as: head, navigation, focus, sidebar, bottom and so on is regarded as independent components, different pages according to the needs of the content, to put related components can form a complete page.2One of the most immediate benefits of modularization and componentization is reuseCopy the code

17. The difference between link and @import in CSS

1. @importAre syntax rules provided by CSS, which only import stylesheets. Link is an HTML-provided tag that not only loads CSS files, but also defines RSS, REL connection properties, and more.2When the page is loaded, the CSS introduced by link is loaded at the same time, and the CSS introduced by @import is loaded after the page is loaded.3The link tag, as an HTML element, does not have compatibility problems, while @import is CSS2.1Unique syntax, unrecognized by older browsers (pre-IE5).4DOM can be manipulated by JS to insert link tags to change the style; Because DOM methods are document-based, you cannot insert styles using @import.Copy the code

18. Write a regular 15-20 digit capital letter or number

var reg = / [^ a-z \ d] 15, 20} {/;
Copy the code

What is the output of the following code

var fullName = 'a';
var obj = {
    fullName: 'b'.prop: {fullName: 'c'.getFullName: function(){
            console.log(this);
            return this.fullName
        }
    }
}
console.log(obj.prop.getFullName());
var test = obj.prop.getFullName;
console.log(test());
Copy the code

The explanation is as follows:

Obj. Prop. GetFullName () herethisIt points to obj. Prop, soconsole.log(obj.prop.getFullName());//'c'test = obj.prop.getFullName; herethisPoint to thewindow, therefore,console.log(test());//'a'
Copy the code

What is the output of the following code

var num = 1;
var myObject = {
    num: 2.add: function() {
        this.num = 3;
        (function() {
            console.log(this.num);
            this.num = 4; }) ();console.log(this.num);
    },
    sub: function() {
        console.log(this.num)
    }
}
myObject.add();
console.log(myObject.num);
console.log(num);
var sub = myObject.sub;
sub();
Copy the code

The explanation is as follows:

var num = 1;
var myObject = {
    num: 2.add: function() {
        this.num = 3;
        (function() {
            // This refers to the window, so the value is 1
            console.log(this.num);
            Num = 4
            this.num = 4; }) ();// this is myObject, so this.num=3
        console.log(this.num);
    },
    sub: function() {
        console.log(this.num)
    }
}
myObject.add();/ / 1 to 3
console.log(myObject.num);/ / 3
console.log(num);/ / 4
// This points to window
var sub = myObject.sub;
sub();/ / 4
Copy the code

21. What does the following code output

setTimeout(function(){
    console.log(1)},0)
new Promise(function executor(resolve){
    console.log(2);
    for(var i=0; i<100; i++){ i==99 && resolve();
    }
    console.log(3);
}).then(function(){
    console.log(4);
});
console.log(5);
Copy the code

The explanation is as follows:

The operation mechanism of setTimeout and setInterval is to remove the specified code from the current execution and wait until the next Event Loop to check whether the specified time is reached. If so, execute the corresponding code; If not, wait until the next round of Event Loop to judge again. This means that the code specified by setTimeout will not execute until all synchronized code has been executed. So the final output1
new PromiseIf yes, execute it immediately. Print it first2.3And then5And then print4And, finally,1So the result is:2.3.5.4.1
Copy the code

22. What are the means of VUE project optimization

Front end:1, route lazy loading2, pictures, resources put CDN3Page pictures are lazy loading4Skeleton screen scheme5Nuxt. js server side: open gzipCopy the code

23, MVC, MVP, MVVM is what

mvc

Model: Data storage View: user interface. Controller: service logicCopy the code

The View sends instructions to the Controller. After the Controller completes its business logic, it asks the Model to change its state. The Model sends new data to the View, and the user gets feedbackCopy the code

mvp

1.Communication between the parts is two-way.2.A View and Model are not connected. They are both delivered by Presenter.3.The View is very thin and does not deploy any business logic, calledPassive viewPassive View, where there is no initiative, whereas Presenter is very thick and all logic is deployed there.Copy the code

mvvm

Changes to the View are automatically reflected in the ViewModel and vice versa.Copy the code

Vue, JQ, React, Angular different advantages

jq

1, need to operate dom frequently2, easy to cause redraw and reflux, affecting page performanceCopy the code

vue

1, MVVM mode, the virtual DOM does not need to operate DOM frequently. Through bidirectional binding, the page changes are driven by data, and the corresponding data also changes. It only needs to pay attention to the business logic of the data layer, without paying attention to the update of the view layer. You can minimize unnecessary update operations and improve DOM rendering efficiency.2, component development, the page is composed of several components, high reusability.3The community environment is good, all kinds of resource documents are very complete.4And throughObjectThe.defineProperty() method, which monitors operations on data so that data synchronization can be triggered automatically.Copy the code

react

1, virtual DOM.2Everything is a component, and component instances can be nested.3, using unique JSX syntax.Copy the code

angular

1AngularJS is expensive to learn, such as adding Dependency Injection, while vue.js provides simple and intuitive apis.2In terms of performance, AngularJS relies on dirty checking of data, so the more Watcher the slower it is.Copy the code

25. What is the virtual DOM, what are its advantages, and where is it stored

Virtual DOM can be understood as a simple JS object, and it contains at least three attributes: tag, attrs and children.Copy the code

Advantage:

1, has the advantage of cross-platform - Because Virtual DOM is based on JavaScript objects and does not rely on the real platform environment, so it has the ability of cross-platform, such as browser platform, Weex, Node, etc.2ยท Improved rendering performance - The advantage of Virtual DOM is not in a single operation, but in a large number of frequent data updates, the view can be reasonably and efficiently updated. In order to realize efficient DOM operation, it is necessary to have a set of efficient virtual DOM diff algorithm. Update the DOM by identifying the nodes that need to be updated this time, and leave the rest unupdated.3, is a JS object stored in memory.Copy the code

Talk about the understanding of Webpack

1The first step in the Webpack implementation of the build will start with the Entry, which can be abstracted into input.2In Webpack everything is a Module, a Module corresponds to a file. Webpack recursively finds all dependent modules starting from the configured Entry.3Chunk: code block. A Chunk is composed of multiple modules for code merging and splitting.4, Loader: module converter, used to convert the original content of the module into new content as required.5Plugin: The extension plug-in broadcasts corresponding events at specific times in the Webpack construction process. The plug-in can monitor the occurrence of these events and do corresponding things at specific times.6, Output: indicates the Output position of the packaged file.Copy the code

27. Talk about Event Loop

๐Ÿ‘‡ juejin.cn/post/684490…

28. This section describes the HTTPS handshake process

1, the client accesses the Web server using the HTTPS URL and requires an SSL connection to the server2After receiving the request from the client, the Web server sends a copy of the certificate (including the public key) of the website to the client3, the client will check the certificate issuing authority and expiration time after receiving the website certificate, and randomly generate a secret key if there is no problem4, the client uses the public key to encrypt the session secret key and sends it to the server. The server decrypts the session secret key using its private key5, and then the server and client use the secret key encryption transmissionCopy the code

Source: muyiy.cn/question/ne…

29. How to defend against CSRF and XSS attacks

XSS attack defense

1HttpOnly prevents Cookie hijacking2Input checking - Don't trust everything the user says3, output check - save when escaping or encodingCopy the code

CSRF attack defense

1Authentication code,2And Referer Check3, add token authenticationCopy the code

Source: juejin.cn/post/684490…

Sort [3, 15, 8, 29, 102, 22] by sort()

var arr = [3.15.8.29.102.22]
Copy the code

A. Use the sort() method directly. The default sort method converts the array elements to strings and then compares the UTF-16 encoding order of the characters in the strings to sort them.

var brr = arr.sort();
console.log(brr);/ /,15,22,29,3,8 [102]
Copy the code

B. sort, which accepts a function that returns a value that compares the relative order of two numbers

var brr = arr.sort((a,b) = >a-b);
console.log(brr);//[3, 8, 15, 22, 29, 102]
Copy the code
  • If the return value is greater than 0, a-b is greater than 0, and A and B switch places
  • If the return value is greater than 0, a-b is less than 0, and a and B remain the same
  • The return value is equal to 0 so a minus b is equal to 0, a and B remain the same

31. Differences between arrow functions and ordinary functions

function data(a,b){
    return a-b
};

var data = (a,b) = >a-b;
Copy the code

A. Arrow functions are anonymous and cannot be used as constructors

let FunConstructor = (a)= > {
    console.log('lll');
}

let fc = new FunConstructor();/ / an error
Copy the code

B, Arrow functions do not bind arguments, instead use rest arguments… To solve

function A(a){
    console.log(arguments);
}
A(1.2.3.4.5.8);  / / [1, 2, 3, 4, 5, 8, the callee: ฦ’, Symbol (Symbol. The iterator) : ฦ’]

let B = (b) = >{
    console.log(arguments);
}

B(2.92.32.32);   // Uncaught ReferenceError: arguments is not defined

let C = (. c) = > {
    console.log(c);
}
C(3.82.32.11323);  // [3, 82, 32, 11323]
Copy the code

C, arrow functions do not bind this. Instead, arrow functions capture the this value of their context as their own

var obj = {
    a: 10.b: (a)= > {
        console.log(this.a); // undefined
        console.log(this); // Window {ฦ’ : ฦ’, blur: ฦ’, focus: ฦ’, close: ฦ’, frames: Window,... }
    },
    c: function() {
        console.log(this.a); / / 10
        console.log(this); // {a: 10, b: ฦ’, c: ฦ’}
    }
}
obj.b(); 
obj.c();
Copy the code

D. Arrow functions that call a function through call() or apply() pass in only one argument.

let obj2 = {
    a: 10.b: function(n) {
        let f = (n) = > n + this.a;
        return f(n);
    },
    c: function(n) {
        let f = (n) = > n + this.a;
        let m = {
            a: 20
        };
        returnf.call(m,n); }};console.log(obj2.b(1));  / / 11
console.log(obj2.c(1)); / / 11
Copy the code

E. Arrow functions have no stereotype attributes

var a = (a)= >{
    return 1;
}

function b(){
    return 2;
}

console.log(a.prototype);  // undefined
console.log(b.prototype);   / / {constructor: ฦ’}
Copy the code

Original address: github.com/liujianxi/s…