Recently, I saw an article summarizing some front-end interview questions, facing the object should be the primary and intermediate front-end of social recruitment, I feel there is certain reference value, so I open a post to try to answer these questions, incidentally as my own interview questions accumulation.

The original link is here

JavaScript based

1, declaration ahead of class problems

Find an article on the Internet, there is a job interview questions, including the definition of variable ascension, this pointer, operator precedence, prototype, inheritance, global variables, pollution, object properties and prototype properties such as many knowledge points, priority is presented and its statement related knowledge in advance, I think there is reference value:

function Foo() {
    getName = function () { alert (1); };
    return this;
}
Foo.getName = function () { alert (2); }; Foo.prototype.getName =function () { alert (3); };var getName = function () { alert (4); };function getName() { alert (5); }// Write the following output:
Foo.getName();
getName(); // The declaration is ahead of schedule
Foo().getName();
getName();
new Foo.getName();
new Foo().getName();
new new Foo().getName();
Copy the code

The answer to this question is: 2, 4, 1, 1, 2, 3, 3.

GetName: getName: getName: getName: getName: getName: getName: getName: getName: getName: getName: getName: getName

var getName = function () { alert (4)};function getName() { alert (5)}Copy the code

In fact, when parsing, it is in this order:

function getName() { alert (5)}var getName;
getName = function () { alert (4)};Copy the code

If we add two more breakpoints in the middle of the code:

getName(); / / 5
var getName = function () { alert (4)}; getName();/ / 4
function getName() { alert (5)}Copy the code

In the first getName, the declaration of function and var is advanced before the first getName, and the assignment of getName is not advanced. The declaration of var alone will not overwrite the variables defined by function. So the first time getName prints function declaration 5; The second getName occurs after the assignment statement, so the output is 4, so the actual code is executed in this order:

function getName() { alert (5)}var getName;
getName(); / / 5
getName = function () { alert (4)}; getName();/ / 4
Copy the code

2. Browser storage

LocalStorage, sessionStorage and cookies

Common: Both are stored in the browser and available only from the same source

  1. Data storage
  • Cookie data is always carried (even if it is not needed) in same-origin HTTP requests, i.e. cookies are passed back and forth between the browser and the server. Cookie data also has the concept of path, which can restrict cookies to a specific path
  • SessionStorage and localStorage do not automatically send data to the server, only localStorage.
  1. Storage data size
  • The storage size limit is also different, cookie data cannot exceed 4K, and because cookies are carried with each HTTP request, cookies are only good for small data, such as session identifiers.
  • SessionStorage and localStorage, while also limited in size, are much larger than cookies, reaching 5M or more
  1. Data Storage Validity Period
  • SessionStorage: only valid until the current browser window closes;
  • LocalStorage: always valid, always saved even when the window or browser is closed, locally stored and therefore used as persistent data;
  • Cookie: Only valid before the set cookie expiration time, even if the window is closed or the browser is closed
  1. Different scope
  • SessionStorage is not shared across different browser Windows, even on the same page;
  • Localstorage is shared in all origin Windows; This means that as long as the browser is not closed, the data still exists
  • Cookie: Is also shared in all the same origin Windows. This means that as long as the browser is not closed, the data still exists

3, cross-domain

Soon I wrote a post summarizing the same origin policy and the various approaches to cross-domain: What is cross-domain, why do browsers prohibit cross-domain, and the divergent learning it causes

4. Use and principle of Promise

Promise is a new feature that ES6 has added to make asynchronous programming problems more reasonable. Ruan yifong explains its usage in detail in the introduction to ECMAScript 6, but I won’t repeat it here.

30 minutes to make sure you understand the Promise principle

The above article is a detailed description of the principle of Promise. Here, I extract the simplest Promise implementation method to illustrate the principle of Promise:

function Promise(fn) {
    var value = null,
        callbacks = [];  // Callbacks are arrays because there can be many callbacks at once

    this.then = function (onFulfilled) {
        callbacks.push(onFulfilled);
    };

    function resolve(value) {
        callbacks.forEach(function (callback) {
            callback(value);
        });
    }

    fn(resolve);
}
Copy the code

First, the single or multiple functions declared in then are pushed into the callbacks list, traversed when the Promise instance calls the resolve method, and passed in the values of the arguments passed in the resolve method.

Here, a simple example is used to analyze the Promise execution flow:

functionm func () {
	return new Promise(function (resolve) {
		setTimeout(function () {
			resolve('complete')},3000);
	})
}

func().then(function (res) {
	console.log(res); // complete
})
Copy the code

The func function is defined to return a Promise instance, which is declared with a resolve callback that takes the resolve function entity in the FN (resolve) definition of the Promise, and an asynchronous operation performed in the callback. The resolve function is executed in the callback after the asynchronous operation completes.

Looking at the execution steps, the func function returns an instance of A Promise that can execute the THEN method defined in the Promise constructor. The callback passed in the THEN method is then executed in resolve (after the asynchronous operation completes), thus implementing the asynchronous callback through the THEN method.

5. JavaScript event loops

The Event Loop mechanism in JavaScript is explained in detail.

JavaScript is a single-threaded, non-blocking language because it was designed to interact with browsers:

  • Single thread:JavaScriptThe reason for the single-threaded design is that, initially, the most it can do is sumDOMTo interact, imagine ifJavaScriptIs multithreaded, so when two threads pair at the same timeDOMPerform an operation, such as one that adds an event to it and another that removes itDOMHow to deal with it? So, in order to make sure that something like this doesn’t happen,JavaScriptChoosing to execute code with only one main thread ensures consistent program execution.
  • Non-blocking: The main thread suspends when the code needs to perform an asynchronous task (a task that does not return results immediately but takes some time to return, such as an I/O event)pending), and then execute the corresponding callback according to certain rules when the asynchronous task returns the result. whileJavaScriptThe way to implement asynchronous operations is to use the Event Loop.
setTimeout(function () {
    console.log(1);
});

new Promise(function(resolve,reject){
    console.log(2)
    resolve(3)
}).then(function(val){
    console.log(val);
})
Copy the code

First, setTimeout and then callbacks in promises are asynchronous methods, while new Promise is a synchronous operation, so this code should immediately print 2; JavaScript divides asynchronous methods into Marco Task (macro task: setTimeout, setInterval, etc.) and Micro Task (micro task: Including New Promise, etc.), in the execution stack of JavaScript, if there are both expired macro tasks and microtasks, all the microtasks will be executed first, and then the first macro task will be executed. Therefore, the callback of then in the two asynchronous operations will be executed first, and then the callback of setTimeout will be executed. So it prints 3, 1, so the final output is 2, 3, 1.

ES6 scope and the difference between let and VAR

Ruan yifeng explains this in detail in the let and const commands section of ECMAScript 6 introduction. Here are some of the key points I think.

ES6 introduces the use of {} wrapped code areas as block-level scope declaration, which has the same effect as ES5 function declared function generated scope, outside the scope can not access the function or variable declared inside the scope. This declaration works in ES6 for blocks of code wrapped in braces, such as for () {}, if () {}, and so on, generating a separate scope.

Compared with var, the new LET in ES6 has the following important features:

  • letDeclared variables are valid only in scope, as shown in the following code:ifThis declaration generates a block-level scope. Variables declared in this scope cannot be accessed outside the scope.
if (true) {
	let me = 'handsome boy';
}
console.log(me); // ReferenceError
Copy the code
  • letThe declared variable andvarError: no variable promotion is generated.
// var case
console.log(foo); / / output is undefined
var foo = 2;
// let
console.log(bar); // ReferenceError
let bar = 2;
Copy the code
  • letDo not allow repeated statements, such as repeated statements will report an error, andvarWhen declaring a variable, the last statement overwrites the first:
/ / an error
function func() {
  let a = 10;
  var a = 1;
}
/ / an error
function func() {
  let a = 10;
  let a = 1;
}
Copy the code
  • As long as the block-level scope existsletCommand, which declares variables that are “bound” (binding) this region, no longer subject to external influence, is a property calledTemporary dead zone.
var tmp = 123;
if (true) {
  tmp = 'abc'; // ReferenceError
  let tmp;
}
Copy the code

7, closures

To be added

8. Prototype and prototype chain

To be added

9. Reflow & Repaint for browsers

Reference: juejin. Cn/post / 684490…

After the browser receives HTML and CSS, the rendering steps are as follows: HTML generates DOM tree through rendering, CSS generates CSS rendering tree through rendering, and the two are combined to generate render tree, and the browser can render the picture according to the Render tree.

What happens when the browser receives a new CSS from the server and needs to update the page? This is reflow versus Repaint. Because browsers reflow before repaint when they rerender a page, redrawing does not necessarily cause redrawing.

Redraw: When the style of the current element (background color, font color, etc.) changes, we just need to rerender the changed element. Redraw has little impact on browser performance. Redraw: change container appearance style, such as background: black, etc. Change the appearance without changing the layout and without affecting the rest of the DOM. Backflow: The process by which the browser recalculates the location and geometry of elements in a document in order to re-render part or all of the document.

Backflow is a performance killer because it can cause the entire DOM tree to be restructured, and the backflow of an element results in subsequent backflow of all of its child elements, as well as the immediate ancestors in the DOM. The changes that trigger the browser reflow are posted below:

  • Page first render
  • The browser window size changed. Procedure
  • The size or position of the element changed
  • Element content changes (number of words or image size, etc.)
  • Element font size changes
  • Add or remove visible DOM elements
  • Activate CSS pseudo-classes (such as: :hover)
  • Query some properties or call some methods

Optimization scheme:

CSS

  • Avoid the use oftableLayout.
  • As far as possible inDOMThe end of the tree changesclass.
  • Avoid setting multiple inline styles.
  • Apply the animation effect topositionProperties forabsoluteorfixedOn the element of.
  • Avoid the use ofCSSExpressions (e.g.calc()).

JavaScript

  • Avoid frequent manipulation of styles; it is best to rewrite them all at oncestyleProperty, or define the style list asclassAnd change it onceclassProperties.
  • Avoid frequent operationsDOM, create adocumentFragmentApply all of them to itDOMAction, and finally add it to the document.
  • You can also set the element firstdisplay: none, and then display it after the operation. Because in thedisplayProperties fornoneOn the element ofDOMThe operation does not cause backflow and redraw.
  • Avoid frequently reading properties that cause backflow/redraw, and if you do need to use them more than once, cache them in a variable.
  • Use absolute positioning on elements with complex animations to keep them out of the document stream, which would otherwise cause frequent backflow of parent elements and subsequent elements.

Deep copy of JS objects

The general idea is to recursively solve, do different processing for different data types:

function deepCopy (obj) {
  let result = {}
  for (let key in obj) {
    if (obj[key] instanceof Object || obj[key] instanceof Array) {
      result[key] = deepCopy(obj[key])
    } else {
      result[key] = obj[key]
    }
  }
  return result
}
Copy the code

This can only copy objects with arrays, objects, or other underlying data types. If there are some complex objects such as RegExp or Date, the result of copying is a {}. This cannot be done properly because there is no separate processing for these special objects. CloneDeep () is an array deep copy method used in lodash. CloneDeep () is an array deep copy method used in lodash. CloneDeep () is an array deep copy method.

In addition, if the object data structure to be copied is relatively simple and there is no data of complex objects, the simplest method can be used:

let cloneResult = JSON.parse(JSON.stringify(targetObj))
Copy the code

11. JS operation accuracy is lost

Previously, I reprinted an article, which has a more detailed explanation of the causes and solutions for the loss of JavaScript operation accuracy: blog.csdn.net/qq_35271556…

Browser dependent

1. The process of the browser from loading to rendering, such as entering a WEB address to display the page

Loading process:

  • The browser resolves the IP address of the domain name based on the DNS server
  • Send an HTTP request to the machine at this IP
  • The server receives, processes, and returns HTTP requests
  • The browser gets what’s returned

Rendering process:

  • Generate a DOM tree based on the HTML structure
  • Generate CSSOM based on CSS
  • DOM and CSSOM are combined to form a RenderTree
  • Start rendering and display according to RenderTree
  • encounter<script>Is executed and blocks rendering

2. Browser caching mechanism

Refer to the article: segmentfault.com/a/119000001…

3. Performance optimization

Reference article: blog.csdn.net/na_sama/art…

Vue

1. Communication mode between components

The official Vue documentation details how components communicate: cn.vuejs.org

Parent component transfers to child component

  • The most common way to do this is to pass in data on a child component label for use inside the child componentpropsReception:
/ / the parent component<template>
  <children name="boy"></children>
</template>
<script>
// Child: children
export default {
  props: {
    name: String}}</script>
Copy the code
  • It can also be used in child componentsthis.$parentAccess the instance of the parent component, but there is a paragraph in the official documentation that makes this very clear$parentMeaning: To use sparingly$parent$childrenTheir primary purpose is as an emergency method of accessing components. More recommended usepropseventsRealize parent-child component communication.

Child component transfers to parent component

  • Typically used in child componentsthis.$emit('eventName', 'data'), and then listens on the child component tag in the parent componenteventNameEvent and gets the value passed in the argument.
/ / child component
export default {
  mounted () {
    this.$emit('mounted'.'Children is mounted.')}}Copy the code
<template>
  <children @mounted="mountedHandle"></children>
</template>
<script>
/ / the parent component
export default {
  methods: {
    mountedHandle (data) {
      console.log(data) // Children is mounted.}}}</script>
Copy the code
  • with$parentThe same is true in the parent component through accessthis.$childrenTo access all child component instances of the component.

Data transfer between non-parent and child components

  • For non-parent components with complex component hierarchy, Vuex can be used to transfer data between components: vuex.vuejs.org/zh/

  • The event bus used in Vue 1.0 has been removed from Vue 2.0. $dispatch and $broadcast are deprecated. Use more concise communication between components and better state management solutions such as Vuex.

2. Principle of bidirectional binding

blog.seosiwei.com/detail/35 blog.seosiwei.com/detail/36 blog.seosiwei.com/detail/37

3. Route navigation hooks

Router.vuejs.org/zh-cn/advan…

The author information

Other Articles by author

  • [Vue] Vue1.0+Webpack1+Gulp project upgrade construction solution stomp road
  • (1) 【JavaScript】
  • What is cross-domain, why do browsers prohibit cross-domain, and the divergent learning it causes