1. How is Vue two-way data binding implemented?The original

  • Vue. js adopts data hijacking combined with publiser-subscriber mode. It hijacks the setter and getter of each attribute through Object.defineProperty() to publish messages to subscribers when data changes and trigger corresponding listening callback
  1. Vue. Js has two core functions: one is a responsive data binding system and the other is a component system.
  2. The accessor property is a special property in an object that cannot be set directly in the object and must be defined separately through the defineProperty() method.
  3. The “value” of the accessor property is special. Reading or setting the value of the accessor property actually calls its internal properties: the get and set functions.
  4. The this inside the get and set methods both refer to obj, which means that the get and set functions can manipulate values inside objects. In addition, accessor properties are “overridden” by common properties with the same name, because accessor properties are preferentially accessed and common properties with the same name are ignored.

Angularjs vs. Vue.js

2. How is minimalist bidirectional data binding implemented?

What are prototypes and prototype chains?The original

We create an object using a constructor:

Each function has a prototype property, which points to an object that is the prototype of the instance created by calling the constructor, namely person1 and person2 in this case. Every JavaScript object (except null) is associated with another object when it is created, and this object is called a prototype, from which each object “inherits” properties.

This is a property that every JavaScript object (except null) has, called __proto__, which points to the object’s prototype.

4. Construcotr, each stereotype has a constructor property pointing to the associated constructor

5, instance and prototype when reading the attributes of the instance, if you can’t find it, you will look for the attributes in the prototype associated with the object. If you still can’t find it, you will look for the prototype of the prototype, until you find the top layer.

How about the Object. Prototype? Object. Prototype = null; Object. Prototype = null

4. Summarize the common new features of ES6.The original

Here are a few common ones:

  • Arrow function
  • Promise
  • Let the Const
  • class
  • modular
  • Function parameter default value
  • Template string
  • Deconstruction assignment
  • Extension operator
  • Short for object property

Arrow function.The original

Arrow functions are not automatically bound to a this object when called. In other words, the arrow function doesn’t have its own this at all. Its this is captured from its context.
  • Called as an anonymous function.

  • Called as a method

  • Is called inside the method

  • Called with the new operator, an error is thrown
  • Use call and apply, bind() calls

To summarize
The arrow function does not have its own this object; it always carries the this object of the external environment. Therefore, whenever this changes in its nearest external environment, the this in the arrow function changes. If the this in its closest environment doesn’t change. So this in the arrow function will not change.

The original

6. What is promise?The original

What is a Prmoise

Promise objects can be thought of as asynchronous operations that are performed once, and they can be used to organize code in a chain of calls

Features of Promise objects:

1. The status of the object is not affected by the outside world.


The Promise object represents an asynchronous operation with three states:


Pending


Resolved, also known as a pity


My rejected!


2. Once the state changes, it will never change again, and this result can be obtained at any time.


There are only two possibilities for a Promise object to change state: from Pending to Resolved and from Pending to Rejected

Disadvantages of Promise objects:

1. You cannot cancel a Promise. Once a Promise is created, it will be executed immediately.


2. If you don’t set a callback function, errors thrown inside a Promise won’t be reflected outside.


3. When in the Pending state, there is no way to know what stage of progress is currently in (just started or nearly completed).

Promise compatibility

Aside from older browsers like Internet Explorer and some lower versions of Android, modern browser support is fine

The use of the Promise

1. Basic Usage:


(1) First we create a Promise and instantiate the Promise


(2) Then the instantiated promise can pass two parameters, resolve after success and Reject after failure


(3) After the Promise instance is generated, the then method can be used to specify the callback functions in Resolved state and Reject state respectively


Promise is more flexible and simpler than callback because it maintains and passes state so that callbacks can be invoked in a timely manner.

Promise. All methods

Promise.all takes an array of Promise objects as arguments. This method returns only when all the Promise objects in the array become resolve.


All takes an array as an argument, p1 and p2 are executed in parallel, and when both are executed, then goes to THEN. All returns all the results in an array, so we print out our results as an array.

Promise. Race method

Race only returns the fastest value, meaning that result returns the one that executes faster.

7. Event bubbling and capture in JSThe original

1, Document to target node, capture forward, encounter registered capture event immediately triggered execution


2, reach the target node, trigger the event (for the target node, it is capture first or bubble first, capture event and bubble event registration order, register first execute)


3. The target node bubbles forward towards the Document direction, and the registered bubbling event is triggered immediately
To sum up:
For non-target nodes, capture is performed before bubbling


For the target node, the event is executed first and registered first, whether bubbling or capturing

8. HTTP and HTTPS

(1) Basic concepts of HTTP and HTTPS

HTTP: Hypertext Transfer protocol, a client – and server-side request and response standard (TCP) transport protocol for transferring hypertext from WWW servers to local browsers.


HTTPS: the HTTP channel aims at security. In short, it is the secure version of HTTP, that is, adding SSL layer under HTTP.


The HTTPS protocol provides the following functions: Establishing a secure information channel to ensure the transmission of arrays and the authenticity of websites.

(2) The difference between HTTP and HTTPS?

HTTPS is a network protocol based on HTTP and SSL to encrypt transmission and authenticate identity. It is more secure than HTTP.

1. The Https protocol requires a CA certificate, which is expensive.


2. HTTP is a hypertext transmission protocol, and information is transmitted in plain text. HTTPS is a secure SSL encryption transmission protocol.


3. The port number varies with the connection mode. Generally speaking, the HTTP port number is 80 and the HTTPS port number is 443


4. HTTP connections are simple and stateless; HTTPS is a network protocol that uses SSL and HTTP to encrypt transmission and authenticate identity. It is more secure than HTTP.

(3) The working principle of HTTPS protocol

The following steps are required when a client communicates with the Web server using HTTPS.

1. If the customer accesses the server using HTTPS URLS, the web server must establish SSL links.


2. After receiving the request from the client, the Web server returns or transmits the certificate of the website (including the public key) to the client.


3. The client and web server start to negotiate the security level of the SSL connection, that is, the encryption level.


4. The client browser establishes a session key based on the security level agreed by both parties, encrypts the session key using the public key of the website, and sends the session key to the website.


5. The Web server decrypts the session key using its own private key.


6. The Web server encrypts the communication with the client using the session key.

9. TCP three-way handshake

The three-way handshake can be simplified as: C initiates a connection request, S confirms the connection, and C confirms the connection. Let’s look at the function of each handshake:

First handshake: S can only accept the packet segment sent by C


Second handshake: C can confirm that S has received the packet segment and can accept the packet segment sent by S


Third handshake: S can confirm that C has received the packet segment

10. Differences between TCP and UDP

  1. TCP is connection-oriented while UDP is connectionless, that is, no link is required before sending data.
  2. TCP provides reliable services. That is to say, data transmitted through the TCP connection is error-free, not lost, not repeated, and in order to arrive; UDP does its best to deliver, i.e. reliable delivery is not guaranteed. And because TCP is reliable, connection-oriented, and does not lose data, it is suitable for large-volume exchanges.
  3. TCP is byte stream oriented, UDP packet oriented, and network congestion does not slow down the transmission rate (hence packet loss, for real-time applications such as IP telephony and video conferencing).
  4. TCP supports only 1 to 1, UDP supports 1 to 1 and 1 to many.
  5. TCP’s header is 20 bytes larger than UDP’s 8 bytes.
  6. TCP is connection-oriented, reliable transport, while UDP is unreliable.

11.Cookie, sessionStorage, localStorage

Common: both are saved in the browser and are of the same origin

Cookie: Cookie data is always carried (even if it is not needed) in a same-origin HTTP request, i.e. cookies are passed back and forth between the browser and the server. However, sessionStorage and localStorage do not automatically send data to the server and only store data locally. Cookie data also has the concept of path, which can limit cookies to belong to a certain path and store them in a small size of 4K or so. (Key: it can be passed back and forth between browser and server, with small storage capacity, only about 4K)

SessionStorage: only valid until the current browser window closed, naturally also cannot be persistent, localStorage: always valid, the window or browser closed is always saved, therefore used as persistent data; Cookies only remain valid until the set cookie expiration time, even if the window or browser is closed. (Key: it is a callback process itself, and disappears after closing the browser. Session is a callback. If the page is different, even if the same page is opened twice, it is regarded as the same callback.)

LocalStorage: localStorage is shared in all origin Windows; Cookies are also shared across all the same origin Windows. (Key: Same-origin Windows are shared and will not be invalidated, regardless of whether the window or browser is closed.)

12. Implement your own bind function

Principle: Through the apply or call method to implement.

PreventDefault and stopPropagation

The event.stopPropagation() method prevents events from bubbling to the parent element, preventing any parent event handlers from being executed. PreventDefault Prevents the default behavior of the element.

For example, blocking submission of a form when the submit button is clicked blocks the following URL link

15. Why closures

Closures are functions that can read variables inside other functions


Closures are useful because they allow you to design private variables and methods.


The three main features of closures are:

1, function nested function


2. Internal functions can access variables of external functions


3. Parameters and variables are not collected.

What’s the difference between call and bind?

The same

Both implement the function of inheriting or converting object Pointers


1. Call and apply can change the direction of this


2. The first argument is the object to which this refers


3. You can use subsequent parameters to continue parameter transmission

The difference between

Call and apply are direct calls to functions. Bind returns a function that does not execute immediately. Instead, it returns a copy of the context-changing function


2. Call and apply can both pass parameters

What is the bind

Bind () creates a new function that, when called, takes the first argument of bind() as this at runtime, followed by a sequence of arguments that precedes any arguments passed


What do you know about front-end performance optimization

The content level

  • Use the CDN
  • A single domain name can reduce the number of DNS searches, while multiple domain names can increase the number of parallel browser downloads. This requires a trade-off. Generally, there should be no more than four resources in a domain.
  • Avoid redirects (by scenario)
  • Avoid 404

The network layer

  • Take advantage of caching and refer to another article on handwriting file servers to talk about front-end and back-end interactions
  • File compression (tell the server what type of compression you support via the response header Accept-encoding: gzip, deflate, BR)
  • Load on demand, extract common code, tree-shaking, etc. (all via WebPack)
  • Reduce cookie size
  • File merge, using CSS Sprite image merge image
  • Preloading files, lazy loading images

Render layers

  • Js at the bottom, CSS at the top
  • Reduce reflow and Repaint
  • Reducing DOM nodes

The code level

  • Cache DOM nodes, reduce node lookups, CSS selector level optimization
  • Reduce DOM node operations
  • Optimize loops by using breaks, continue, return, etc
  • React uses methods such as event delegation and object pooling

18. Talk about reflow and Repaint for browsers

Browser parsing process

Parsing the HTML generates a DOM tree


Parsing the CSS


Apply CSS to the DOM tree to generate the Render tree (which records each node with its style and location).


Render the Render tree to the page

Reflow (back)

Reflow translates to reflow, which means the page builds the Render tree again. Reflow occurs at least once per page, when the page is first loaded. Reflow occurs when there are any changes in the page that may result in a change in the structure of the document (i.e. a change in the relative or absolute position of elements).

Changing the size or position of an element changes the browser window (triggered by the resize event)

Repaint (redraw)

Repaint translates to repaint, which is analogous to step 4 above, drawing pages from the Render tree with less performance loss than backflow. Redraw must occur with each reflux. In addition, the following operations (those that do not affect the structure of the document, and those that do will backflow) will also redraw:

Element color, opacity changes to text-align, etc

19. Deep copy

function deepcopy(obj) {
        let res = {};
        for (key in obj) {
            if (typeof obj[key] == 'object') {
                res[key] = deepcopy(obj[key]);
            } else {
                res[key] = obj[key];
            }
        }
        return res;
    }
Copy the code

20. The difference between defer and AsyncThe original

define

Defer: This Boolean property is set to instruct the browser that the script executes after the document has been parsed.


Async: Sets this Boolean property to indicate that the browser should execute the script asynchronously if possible.


1. In the case of defer, we can assume that we put the js from the outer chain at the bottom of the page. Loading js does not block page rendering or resource loading. However, defer will be executed in the same order as the original JS, so you can safely use js that have dependencies.


2. For async, this is a new property in HTML5, which is used to load and execute scripts asynchronously without blocking the page loading because of loading scripts. In the case of async, js will be executed as soon as it is downloaded, so it may not be executed in the original order. If js has dependencies, async is more likely to fail.


The difference between

Similarities:

1. Load files without blocking page rendering


2. Invalid for inline scripts


3. The document.write method cannot be called in scripts that use these two properties


4. Event callback for scripted onload

Difference:

1. The version of HTML, HTML4.0, defined defer; Html5.0 defines async


2. Browser compatibility


3. Execution time Each async script is executed immediately after it finishes downloading and before the Window load event. So it’s possible to get scripts out of order; Each script for the defer property is executed in the original order after the page has been parsed, and before the Document’s DOMContentLoaded.

conclusion

1. If async is true, the script is executed asynchronously after downloading.


2. If async is false and defer is true, the script will execute after the page has been parsed.


3. If async and defer are both false, the script will stop the page parsing in the page parsing, download and execute immediately.

Finally, I would like to give some personal advice. Whether to use defer or async attributes, you need to sort out THE JS files in the page first, which files have dependencies among them, which files can be delayed loading, etc. Merge and split THE JS code well, and then use these two attributes according to the needs of the page.

21, Detail toString

The toString() method returns a string representing the object. The valueOf() method returns the original valueOf the specified object.

22, how to remove the first space of a string?

/ / es6 'ab'. The trim () / / / / "ab" regular "ab", the replace (/ ^ | \ \ s * * $s/g, ' ') / / "ab"Copy the code

23. Jsonp principle? Weaknesses?

How it works: Use script tag to achieve cross-domain access, you can specify the callback function in the URL, get JSON data and execute jSOP in the specified callback function. Disadvantages: JSONP only supports GET, which is a script injection behavior and has some security risks. No error is reported if the returned data format is faulty or if the return fails.

24. Design patterns

Function People() {var obj = new Object(); Obj. Name = 'xiaomin '; obj.age = 12; obj.say = function() { // alert(this.name); return this.name; } return obj; } function People() {this.name = 'my.name '; this.say = function() { return this.name; Function People(name) {this.name = name; } People.prototype.sayName = function() { console.log(this.name); }Copy the code

25, inheritance,

Function People(name) {this.name = name; } People.prototype.sayName = function() { console.log(this.name); } function Student(name, grade) { this.name = name; this.grade = grade; this.sayGrade = function() { console.log(this.grade); } } Student.prototype = new People(); Function People() {this.name = name; } People.prototype.sayName = function() { console.log(this.name); } people.prototype. type = function() {console.log(' People '); }; function Student(name, grade) { this.name = name; this.grade = grade; People.apply(this); } var student = new student (' c ', 5); student.type();Copy the code

26, HTTP request method uses

1. GET method

Sends a request to retrieve a resource on the server

2. POST method

Submits data or appends new data to the resource specified by the URL

3, PUT method

Much like the POST method, it wants to submit data to the server. But there are differences. PUT specifies the location of the resource on the server, whereas POST does not

4, HEAD method

Only the header of the page is requested

5. DELETE method

Example Delete a resource on the server

6, OPTIONS method

It is used to get the methods supported by the current URL. If the request is successful, there will be an Allow header containing information like “GET,POST”. The browser must first issue a preflight request using the OPTIONS method to know whether the server will Allow the cross-domain request. The actual HTTP request is made only after the server confirms that it is allowed.

7. TRACE methods

The TRACE method is used to fire a remote, application-level request message loop

8. CONNECT method

Convert the request connection to a transparent TCP/IP channel

27, Enter the URL from the browser address bar to display the page steps

  • The browser sends the requested URL to the DNS for domain name resolution, finds the real IP address, and sends a request to the server. link
  • The server to the background processing completed after the return of data, browser to receive files (HTML, JS, CSS, images, etc.);
  • The browser parses the loaded resources (HTML, JS, CSS, etc.) and establishes the corresponding internal data structure (such as HTML DOM).
  • Load the parsed resource file, render the page, and finish.

How to optimize website performance

1. The content aspect

  • Reduce HTTP requests: merge files, CSS sprites, inline images

  • Reduce DNS queries: DNS caching, distributing resources to the appropriate number of host names

  • Reduce the DOM element count

2. The Server side

  • Use the CDN

  • Configure the ETag

  • Use Gzip compression for components

3. The cookies

  • Reduce cookie size

4. The CSS

  • Place the style sheet at the top of the page
  • Do not use CSS expressions
  • Use do not use @import

5. Javascript

  • Place the script at the bottom of the page

  • Bring in javascript and CSS from the outside

  • Compress javascript and CSS

  • Delete unnecessary scripts

  • Reducing DOM access

6. Pictures

  • Optimize picture: select color depth and compression according to actual color needs
  • Optimizing CSS Sprites
  • Do not stretch images in HTML

29. HTTP status codes and their meanings

1XX: indicates the information status code

100 Continue When a POST request is sent, the server sends an acknowledgement message after the HTTP header has been sent, and then sends specific parameter information

2XX: success status code

200 OK A normal message is displayed

201 Created The request succeeds and the server creates a new resource

202 Accepted the request has been Accepted but not yet processed

3XX: redirection

301 Moved Permanently The page for the Permanently Moved Permanently to the new location.

302 Found Temporary redirect.

303 See Other Temporary redirects and always uses GET to request new URIs.

The requested page has Not been Modified since the last request.

4XX: Client error

400 The Bad Request server cannot understand the format of the Request. The client should not attempt to use the same content to initiate a Request again.

401 Unauthorized The request is not authorized.

403 Forbidden Forbidden access.

404 Not Found The resource how to match the URI was Not Found.

5XX: Server error

500 Internal Server Error Common Server errors.

503 Service Unavailable The server cannot process the request temporarily (possibly due to overload or maintenance).

What built-in objects does JS have?

  • Object is the parent Object of all objects in JavaScript

  • Data encapsulation class objects: Object, Array, Boolean, Number, and String

  • Other objects: Function, Arguments, Math, Date, RegExp, Error

JavaScript base data types and reference data types? Can you draw their memory map?

  • Stack: primitive data type (Undefined, Null, Boolean, Number, String)
  • Heap: Reference Data types (Object, Array, Function, Data)
  • The difference between the two types is: storage location is different;
  • Primitive data types are directly stored in simple data segments in the stack, occupying small space and fixed size. They are frequently used data, so they are stored in the stack.
  • Reference data type Objects stored in the heap occupy large space, size is not fixed, if stored in the stack, will affect the performance of the program; The reference data type stores a pointer on the stack to the starting address of the entity in the heap. The difference is that you cannot directly access locations in the heap space and manipulate the heap space. Only reference addresses of objects in stack memory can be manipulated. link

Summarize the difference between

  • Different memory allocations when declaring variables:
  • Different memory allocation mechanisms lead to different access mechanisms
  • The difference between copying a variable
  • Differences in parameter passing (the process of copying arguments to parameters)

33, [“1”, “2”, “3”].map(parseInt)

  • [1, NaN, NaN] Because parseInt takes two arguments (val, radix), where radix denotes the radix used for parsing.

  • Map passed 3 elements (Element, index, array), and the corresponding radix was illegal, resulting in the failure of parsing.

34, The difference between synchronous and asynchronous?

  • Synchronization: When the browser requests the server, the user sees the page refresh and sends the request again. After the request is complete, the page is refreshed and the user sees the new content and performs the next operation
  • Asynchronous: The browser requests from the server. The user performs normal operations and the browser requests from the back end. When the request is finished, the page is not refreshed, the new content will also appear, and the user will see the new content

35, Talk about the difference between let and VAR?

  • The let command does not have variable promotion and will cause an error if used before let
  • If there are let and const commands in the block, a closed scope is formed
  • Duplicate declarations are not allowed, so arguments cannot be redeclared inside functions

36. Browser compatibility problems

  • WeChat H5

Scrolling for webkit-overflow-scrolling: touch 2. Cursor: Pointer does not work on IOS when using bootstrap mode

  • Wechat applets
  1. The gap between the top and bottom images, set img to display:block;
  2. Button border: after{border:none; }

Judge an array

  • arr instancof Array
  • Array.isArray(arr)
  • Object.prototype.toString.call(arr)=='[Object Array]’

38, How to ensure that the properties of a variable are not modified

const object1 = { property1: 42 };

const object2 = Object.freeze(object1);

object2.property1 = 33;

39. Splice and slice and substring and substr

classification Change the original data The name of the The first parameter Second parameter The third parameter
Array methods change splice Start (can be negative) len add
Array methods Don’t change slice start end
String method Don’t change substring start end
String method Don’t change substr Start (can be negative) len

40, array deduplication

  • […new Set(arr)]
  • Array.from(new Set(arr))