First, JS correlation
1. The closure
- Overview: Closure is a way to access a function’s scope from outside the function. The function is nested inside the function, and the inner function is called by the inner function to call the local variable of the outer function.
- Advantages: Scope isolation without global contamination.
- Disadvantages: Because closures reside in memory for long periods of time, this can lead to memory leaks over time.
- How to fix memory leaks: Set null to closure variables that expose all the outside.
- Application scenario: Encapsulates components, combines for loops with timers, and combines for loops with DOM events. In the process of performance optimization, the use of throttling function, navigation bar to obtain the use of subscripts.
- Ps: Closures are designed to extend the life of local variables.
2. What is the understanding of prototype chain in JS?
2.1 What are prototypes and prototype chains
-
The prototype
① All reference types have a __proto__ attribute whose value is a common object. ② All functions have a prototype attribute whose value is a normal object. ③ The __proto__ attribute of all reference types points to the prototype of its constructor.Copy the code
var a = [1.2.3]; a.__proto__ === Array.prototype; // true Copy the code
-
Prototype chain
When accessing a property of an object, it looks first at the property itself. If not, it looks at its __proto__ implicit prototype, the constructor's prototype. If not, it looks again at the constructor's __proto__. And so you go up layer by layer and you create a chain, which we call a prototype chain.Copy the code
For example, there is the following code
Undefined ② object.prototype. __proto__ === null ②Object.prototype.__proto__ == null Points to the object that triggered the current event execution.Copy the code
3. Talk about JS inheritance (including ES6)
3.1 What is Inheritance
Giving one object access to properties and methods in another object.
3.2 How to Implement Inheritance
Constructor inheritance, stereotype inheritance, stereotype chain inheritance, copy inheritance (mixin inheritance: mixin).
- Prototype inheritance
Make the prototype of the new instance equal to the instance of the parent class
function Person(name) {
this.name = name
this.sun = function () {
console.log(this.name)
}
}
Person.prototype.age = 10
function Fly() {
this.name = 'fly'
}
Fly.prototype = new Person()
var fly = new Fly()
console.log(fly.age) / / 10
console.log(fly instanceof Person) // true
Copy the code
- Features: Instance inheritable properties are: constructor properties of instance, constructor properties of parent class, stereotype properties of parent class. (The new instance does not inherit the instance attributes of the parent class.)
- Disadvantages:
- The new instance cannot pass arguments to the parent constructor.
- Unitary inheritance.
- All instances share the attributes of the parent instance, and the attributes on the stereotype are shared; one instance changes the stereotype attributes, and the other instance changes the stereotype attributes.
- Prototype chain inheritance
Use call and apply to introduce a superclass constructor into a subclass function.
function Person(name) {
this.name = name
this.sun = function () {
console.log(this.name)
}
}
Person.prototype.age = 10
function Fly() {
Person.call(this.'fly')
this.age = 18
}
var fly = new Fly()
console.log(fly.name) //fly
console.log(fly.age) / / 18
console.log(fly instanceof Person) // false
Copy the code
- Features:
- Only the attributes of the parent constructor are inherited, not the attributes of the parent stereotype.
- The shortcomings of prototype chain inheritance are solved.
- Multiple constructors can be inherited (call multiple.
- A child instance can pass arguments to its parent.
- disadvantages
- Only the attributes of the parent constructor are inherited.
- Unable to reuse instance constructors.
- Each new instance has a copy of the superclass constructor.
- Combinatorial inheritance (stereotype chain inheritance + constructor)
function Father(name) {
this.faName = 'Father'
}
Father.prototype.getfaName = function () {
console.log(this.faName)
}
function Child(args) {
this.chName = 'Child'
Father.apply(this[]),// Call the parent constructor a second time
}
Child.prototype = new Father() // Call the parent constructor for the first time
Child.prototype.constructor = Child
Child.prototype.getchName = function () {
console.log(this.chName)
}
Copy the code
- Disadvantages:
- The superclass constructor is called twice :(first while the subclass prototype is being created, and then again inside the subclass constructor).
- Subclasses inherit attributes from the parent class, one set on the subclass instance and one set on the subclass prototype (creating unnecessary redundant attributes on the subclass prototype) (masking attributes on the instance from the stereotype).
- Es6 inheritance
Es6 inheritance is a relatively new and mainstream inheritance method. Classes are defined with class, classes are extended with extends, and super() is used to represent the parent class.
class Person {
// Private attributes are defined in the constructor
constructor(name, age) {
this.name = name
this.age = age
}
// Public method
say() {
console.log(this.name, this.age)
}
}
class LS extends Person {
constructor(name, age, job) {
super(name, age)
this.job = job
}
}
const ls = new LS('bill'.20.'the web front end')
console.log(ls.name, ls.age) / / li si 20
console.log(ls.job) / / web front end
Copy the code
4. How to bind JS native events
There are three types of JS native binding events:
- HTML event handler
- DOM0 level event handler
- Dom2-level event handler
- HTML event handler
HTML events are now no longer needed, which is to add events directly to various HTML tags, similar to CSS inline style, but the disadvantage is that it is not easy to maintain, because scattered in the tag, that is, the coupling degree is too high. Such as:
<button onclick="Event Handler">Am I</button>
Copy the code
- DOM0 level events, currently used in the PC side or more binding events, compatibility is good, mainly to obtain dom elements first, and then directly add events to dom elements. Such as:
var btn=document.getelementById (' ID element ') btn.onclick=function() {
// The event logic to process
}
// How to remove DOM0 event? Simple: btn.onclick=null; I'll just leave it blank
Copy the code
- Advantages: Good compatibility
- Disadvantages: supports bubbling only, does not support capture
- Dom2-level events, which are more commonly used on mobile devices, also have many advantages, providing specialized binding and removal methods. Such as:
var btn=documentDocument.getelementbyid (' id element)// Bind eventsBtn. addEventListener(' click ', the name of the bound event handler,false)
// Remove the eventBtn. removeEventListener(' click ', the name of the event handler to remove,false)
Copy the code
- Benefits: Support for binding multiple events to an element, support for bubbling and capturing event mechanisms.
5. What are the native DOM manipulation methods of JS?
- Looking for:
- getElementByid
- getElementsByTagName
- querySelector
- querySelectorAll
- Insert:
- appendChild
- insertBefore
- Delete:
- removeChild
- Cloning:
- cloneNode
- Set and get properties:
- SetAttribute (” Attribute name “, “value”),getAttibute(” attribute name “)
6. What are the new ES6 features?
- New let and const declaration keywords are added to the variable section to implement block-level scope for variables.
- New arrow function. The arrow function this points to a fixed position.
- New extension operator (…) , to take revenue arguments, expand arrays/JSON, etc.
- New template string (
${variable name}
) - New json serialization json.stringify (json) and deserialization json.parse (jsonStr)
- For better object orientation, add class constructor extends super to support object oriented development.
- modular
- Asynchronous operation Promise
- Babel compilation, ES6 is not compatible with some browsers of lower versions, you can use Babel compilation, contains ES6 code js files, compiled into ordinary JS code files.
7. What are the JS design patterns (singleton pattern observer pattern, etc.)
There are many JS design patterns, but I know of singleton patterns, observer patterns
- Singleton mode: to ensure that a class has only one instance, the implementation method is generally to determine whether the instance exists, if there is a direct return, if there is no to create and return, this ensures that a class has only one instance object. In JavaScript, a singleton acts as a namespace provider, providing a unique access point to the object from the global namespace.
- Observer mode: The observer mode should be used when changes to one object require changes to other objects, and it is not known how many objects need to be changed.
In general, what the observer pattern does is decouple, making both sides of the coupling dependent on abstraction rather than concrete. So that the changes in each side don’t affect the changes in the other side.
8. Describe your understanding of JS object-oriented
- define
- Objects: Everything is an object
- Class: A subdivision of an object
- Instance: a concrete thing in a class
- Take ES object-oriented as an example
Es6 uses the class keyword to define classes
class Person {
// Private attributes are defined in the constructor
constructor(name, age) {
this.name = name
this.age = age
}
// Public method
say() {
console.log(this.name, this.age)
}
}
class LS extends Person {
constructor(name, age, job) {
super(name, age)
this.job = job
}
}
const ls = new LS('bill'.20.'the web front end')
console.log(ls.name, ls.age) / / li si 20
console.log(ls.job) / / web front end
Copy the code
- Features:
- The es6 class now has a constructor, which is separate from the class, to define methods: no longer need a stereotype to define methods.
- Es inheritance: extends inheritance, super super.
- This in the constructor refers to the instance object being created.
- This refers to whoever calls this method.
9. Describe the common methods of javascript arrays (at least 6)
Array in development, use frequency is frequent, JS array of commonly used methods are: push, pop, unshift, shift, splice, join, concat, forEach, filter, map, sort, and some, every lot, But are usually very common development methods, you can add a little ES6.
10. What are the differences between javascript array built-in traversal methods
Javascript array built-in traversal (traversal is the meaning of loop) methods mainly have:
-
ForEach replaces the for loop by iterating over the array and returns undefined.
let arrInfo = [4.6.6.8.5.7.87] // item: each item traversed by the code, // index: represents the index of each item traversed, // arr: represents the array itself arrInfo.forEach((item, index, arr) = > { // iterate over the logic }) Copy the code
-
Filter is a method that filters traversal and returns a new array that meets the condition true if it returns true.
let arrInfo = [4.16.6.8.45.7.87] let resultArr = arrInfo.filter((item, index, arr) = > { For example, return an array whose value is greater than 9 return item > 9 }) Copy the code
-
map
The map method is mainly used for complex logic processing of arrays, especially for data traversal in React. It is similar to forEach.
- some
This some method is used to return true as long as there is at least one result in the array, otherwise fasel is returned, similar to forEach.
- every
The every method returns true only if each item in the array meets the criteria, and false otherwise, just like forEach.
11. Talk about JS scopes and scope chains
JS scope is the scope that JS identifies variables, and scope chain is the order in which JS looks up variables.
-
Scope: JS scopes mainly include global scopes, local scopes and ES6 block-level scopes
- Global scope: That is, the scope of variables defined under the window, accessible from anywhere.
- Local scope: is a range of variables defined only inside a function.
- Block-level scope: Simply put, variables defined in let and const in any code block are considered block-level variables, such as let variables in for loops, let variables in if statements, and so on.
- Note: try not to use global variables, because it is easy to cause global pollution, naming conflicts, bad for bug search.
-
Scope chain: The so-called scope chain is the process of finding variables from the innermost scope to the outermost scope. The resulting chain is the scope chain.
12. Tell me what happens between entering the URL and loading the page.
- The DNS
- A TCP connection
- Sending an HTTP request
- The server processes the request and returns the required data
- The browser parses the rendered page
- Connect the end of the
- Enter a domain name, domain name to find the DNS server address (IP) corresponding to the domain name, through THE TCP request link service, through the WEB server (Apache) to return data, the browser according to the returned data to build a DOM tree, through the CSS rendering engine and JS parsing engine to render the page, close the TCP connection.
13. What is JS event delegate (also called event delegate)?
The JS event broker binds events to parent elements (e.g. Ul) and does not bind events to child elements (e.g. Ul). The main purpose is to improve performance, because I don’t need to bind events to each child element. I only bind the parent element once, which in native JS is through the event object.
-
Targe property implementation
var ul = document.querySelector("ul"); ul.onclick = function(e){//e stands for event, the event object var target = e.target || e.srcElement; //target gets the target that triggers the event (li) if(target.nodeName.toLowerCase() == 'li') {// The target (li) node name is changed to lowercase or uppercase if not alert(target.innerHTML) } } Copy the code
-
Jq way
$(” ul “).on(” click “, “li”,function(){// event logic})) where the second argument refers to the specific target of the event, especially to the dynamically added element binding event, which is particularly useful.
14. What are the JS data types?
- Basic data types: number, string, Boolean, null, and undefined, symbol (new) ES6
- Compound types: Object,function
15. Talk about the difference between call,apply, and bind
Call,apply, and bind are all used to change the direction of this.
- The main difference between Call and apply is that the parameters passed after call are separated by commas, while the parameters passed by apply are arrays.
- Bind (obj, argument 1, argument 2,)(). Bind can only be comma-separated and cannot be an array.
Second, git related
1. How do you manage projects in your company?
Project version control is mainly done through Git.
How many git commands do you use?
- git add
- git status
- Git commit -m
- git pus
- The git pull etc.
3. Talk about how to resolve conflicts if multiple users operate the same file.
When a conflict occurs when multiple people collaborate to modify the same file, I first git pull the remote file down, manually modify the conflicting code, then git add,git commit,git push and upload it to the remote repository. If the conflict is not triggered by pull, you can save it temporarily through git Stash first, then pull it out, then pull it out, and then commit it manually.
Third, Ajax related
1. Describe how you interact with backend data.
For data interaction with the back end through Ajax, the unified interface document can be used to realize the efficient development of the front and back ends. If the interface document cannot be specified in detail, or the parameters in the interface document cannot request data, I will actively communicate with the back end engineer until the business development related to interface is completed. Of course, in order to verify some interface problems, some auxiliary tools are used, such as runAPI, an online testing tool.
2. How do you work if the back-end data interface is not ready?
If the backend interface is not ready to, I will communicate with the back-end engineer, the format of the data returned by setting interface, and then the front through some mock data tools (the last company is using a easymock, thief simple) to mass produce false data, can let the front-end and back-end development at the same time, without having to wait for the back-end data interface to write good development again, This improves the overall development efficiency of the project.
3. What is your understanding of ajax’s same-origin policy?
Ajax same-origin policy for security reasons, Ajax does not allow access to resources under different domain names.
4. Describe the situations where cross-domain and cross-domain solutions and implementation principles arise.
Cross-domain occurs when different protocols, domain names, ports, and domain names and IP addresses are accessed.
5. Cross-domain solutions There are three mainstream solutions
Cross-domain is a limitation imposed by the browser, not the back end.
- jsonp
Jsonp implementation principle: It is mainly used to dynamically create a Script tag to request the address of the back-end interface, and then pass the callback parameter, and the back-end receives the callback. After data processing, the back-end returns the form of callback function call, and the parameter in the callback is JSON. Proxy (front-end proxy and back-end proxy) Front-end proxy IN VUE I mainly through the vue scaffolding in config index file to configure, where there is a proxyTable to configure cross-domain proxy. 3. CORS The full name of CORS is cross-domain resource sharing. It is mainly used by background engineers to set back-end codes to achieve front-end cross-domain requests.
- Note: Today’s mainstream frameworks are implemented across domains using proxies and CORS.
6. Talk about the interaction process (i.e. flow) of native Ajax
- Start by creating an XHR object called XMLHttpRequest().
- Then open is ready to send. Open has three parameters: get and POST, interface address, and synchronous and asynchronous.
- The third step is to send.
- Onreadystatechange (); onreadyStatechange (); onreadyStatechange ();
7. Tell me your understanding of synchronous and asynchronous
-
Sync is the execution of code line by line. The following code and request will not be executed until the previous code and request are executed.
- Disadvantages: Easy to cause code blocking.
- Pros: Easy for programmers to understand (because code is executed line by line from top to bottom, emphasizing order).
-
Asynchronous: async, which means that code can execute code after the current program has not finished executing.
- Disadvantages: difficult for programmers to understand (because it is not executed sequentially).
- Advantages: It can solve the problem of code blocking and improve the efficiency and performance of code execution.
-
There are three main asynchronous solutions:
- The callback function
- I promise.
- The generator (understand)
- Async and await
8. How to solve ajax cache?
This method is implemented by adding a random number (also known as file fingerprint) to the end of the file name. The main principle is that the browser first checks whether the url of the file requested for the second time has been cached in the browser. If it has been cached, the url will be used.
9. What technologies are used in javaScript native,jQuery, Vue, React, ajax and background interaction
- JavaScript native Ajax: XMLHttpRequest objects are used.
- In the jQuery Ajax: Ajax (),, Ajax (), Ajax (), the getJSON (),, get (), the get (),, get (), post (), etc.
- Ajax in VUE: Vue-Resource (in Vu1.x), Axios (mainstream).
- Wx.request () is similar to jquery’s $.ajax(), with parameters url,success, data,method,fail, etc.
10. Tell me what you know about HTTP status codes.
- 1XX (Interim response)
A status code that represents a temporary response and requires the requester to continue executing the operation.
- 2XX (Success)
A status code indicating that the request was successfully processed. Common status codes starting with 2 are:
- 200 – The server returns to the web page successfully.
- 3xx (Redirection)
Indicates that further action is required to complete the request. In general, these status codes are used to redirect common 3-word status codes:
- The page for request 301 (Permanent move) has been permanently moved to a new location. When the server returns this response, the requester is automatically forwarded to a new location.
- The 302 (temporary mobile) server currently responds to requests from web pages in different locations, but requesters should continue to use the original location for future requests.
- 304 (Unmodified) The requested page has not been modified since the last request. When the server returns this response, the web page content is not returned.
- 4XX (Request error) These status codes indicate that the request may be in error, preventing the server from processing it.
Common four-letter states are:
- 404 – The requested page does not exist
- 5xx (Server error)
These status codes indicate that an internal error occurred while the server was trying to process the request. These errors may be server errors rather than request errors. Common status codes starting with 5 are:
- 500 (Server internal error) The server encountered an error and could not complete the request.
- 503 (Service unavailable) The server is currently unavailable (due to overloading or downtime for maintenance). Usually, this is a temporary state.
11. Deep copy, shallow copy
Use es6 object. assign({},{}) to merge objects. For arrays, use ES6 array. from, or the EXTENSION operator… Arr, if using ES5 you need to do a loop to make a shallow copy, and if using deep copy you need to do a recursive form. It is also possible to implement deep copy using json.parse (json.stringify (object)).