1. What is a prototype, a prototype chain, and what does it do?
A: Prototype: Each object is associated with another object, and that associated object is called a prototype. For example, the Person function has a prototype property that points to an object, which is meaningless for ordinary functions but useful for constructors. When the new operator is used, the Person. Prototype is assigned to the __proto__ property of the instance.
JS has a prototype lookup mechanism, which puts a method originally defined on the instance into the prototype object. The new operation of the constructor assigns the prototype object to the __proto__ attribute of the instance, so when a method is called using the returned instance, if the instance itself is not available, To automatically go to the instance __proto__ to find, so as to achieve method reuse, reduce memory overhead.
Prototype chain: Each object has a prototype object associated with it. This prototype object is also a common object, and this common object also has its own prototype object. In this way, a chain is formed, and this chain is the prototype chain. Through the prototype chain can achieve JS inheritance, the parent class of the prototype object assigned to the child class of the prototype, so that the child class instances can access the parent class of the prototype method.
1 Person.prototype.constructor == Person2 3 Person.prototype.__proto__.constructor == Object 4 5 Person.prototype.__proto__ == Object.prototype6 7 Object.prototype.__proto__ == null
Copy the code
How to implement inheritance (ES5/ES6)?
10 function Anima(name){this.name = name; Function (){15 console.log(this.name) 16} 17 18 function Person(name,age){// subclass 19 Anima.call(this,name); 20 this.age = age; 21 } 22 23 Person.prototype = Object.create(Anima.prototype, { 24 constructor: { 25 value: Person, 26 enumerable: false 27 } 28 }) 29 30 31 var p = new Persion("haha",12); 32 Extends //ES6 12345678910111213141516171819202122232425Copy the code
Click here to get the video course on web Front-end Full Stack Architecture
3. What are scopes and scope chains?
A: Scope refers to the area in the program source code that defines variables. It limits the scope that a variable can access. The essence of scope is an object. In the lexical scope adopted by JS, the scope is already defined when the code is written (when the function is defined). In ES6, there are 3 scopes: global globel, function scope, fast scope ({}) (eval)
Scope chain: A chain structure with multiple levels of scope objects referenced step by step. The scope property of the execution context stores all variables, including local and global variables, and controls the order in which variables are used.
var b = 10; //1: output? Function b(){b = 20; console.log(b); }) (); var b = 10; Function b(b) {function b(b) {function b(b) {function b(b) {function b(b) {function b(b) {function b(b) { window.b = 20; Console. log(b) // output 10})(b) 1234567891011 var a = 10; (function () { console.log(a) a = 5 console.log(window.a) var a = 20; console.log(a) })() 12345678Copy the code
4. What are closures, and what are their advantages and disadvantages?
A: A closure is created when a function can remember and access an external scope, and that external scope is called a closure.
Cause: The outer function’s scope object cannot be released. Function: Protect a variable and reuse a variable. Disadvantages: Improper use, will cause memory leaks.
Function A and function B are called closure when the inner function B refers to A local variable of A because JS is A lexical scope and B’s scope chain has A reference to A’s execution environment (this execution environment is represented by functions), so A’s execution environment AO is not recycled.
5. What is this and what are the common ways of this? How do I change the direction of this?
A: JS generates an execution context during execution. Context records information such as where the containing function is called, scope, and this. This is one of the context properties, and it’s used during the execution of the function. This is bound at run time, and the context object it refers to depends on various conditions of the function call. This provides an elegant way to implicitly pass a reference to an object, so using this in functions makes it easier to reuse functions.
This === window; this === window; this === window 5. This in the DOM event handler refers to the current DOM node. 6. The bind, call, apply operator sets this to this in the bind: function and returns the new call, apply function: The arrow function does not have its own this, the parent scope of this
var x = 3; var foo = { x: 2, baz: { x: 1, bar: function() { return this.x; } } } var go = foo.baz.bar; go()? foo.baz.bar()? Function Foo() {foo. a = function() {console.log(1)} this.a = function() {console.log(2)}} foo.prototype.a = function() { console.log(3) } Foo.a = function() { console.log(4) } Foo.a(); let obj = new Foo(); obj.a(); Foo.a(); 12345678910111213141516171819202122232425262728293031323334353637Copy the code
6. Hand write bind, call, apply functions
Answer: These are all methods on the Function prototype.
Function.prototype.myCall = function(context,... Args){var fn = this; context.fn = fn; context.fn(... args); Delete the context, fn} Function. The prototype. MyBind = Function (context) {/ / bind returns the new executive Function / / figure out whether the caller Function if (typeof this! = 'function'){throw new Error("Error")} let args = [...arguments].slice(1); var _this = this; Return function F() {return _this.apply(context,args.concat([...arguments]))}} 1234567891011121314151617181920Copy the code
7. What is deep and shallow copy, please write the code
A: Shallow copy is a copy of an object whose attribute value does not refer to a type. Object.assign iteration (for… In the for… Of Object.enteries) extension operators, etc.
If the object also contains a reference type, copying the reference type together is called a deep copy. JSON object methods (ignoring functions and null attributes), recursive.
Var newObj = array.isarray (obj)? [] : {}; If (obj && typeof obj == "object"){// Iterate for(var key in obj){if(typeof obj[key] == 'obj'){newObj[key] = deepCopy(obj[key]) }else{ newObj[key] = obj[key] } } } return newObj } 123456789101112131415Copy the code
What is Ajax and how do you encapsulate it? What is the difference between a Get request and a Post request?
A: Ajax stands for asynchronous JS and XML technology, which allows web pages to be asynchronously updated by exchanging data with backend servers, meaning local updates to web pages without reloading the entire page.
1. Nex XMLHttprequset object 2. Open (method, URL, false) 3. Bind the redayStatechange event 4. Call the send method. If it is a POST request, the parameters can be passedCopy the code
In addition to the common Get and Post, the front-end request methods include Update, Delete, and PUT (restful API design). Get requests can be cached and stored in the browser history. The parameters of the request are directly followed by the URL, so sensitive data should not be transmitted. GET requests are limited in length (2048 characters), 2k for IE and Safari; Opera limit 4 k; Firefox, Chrome limit 8K. GET requests should generally only be used to GET data from the background.
POST requests are not cached, they are not retained in browser history. POST requests have no requirement for data length. POST requests are typically used to submit data to the background.
9. Say something about the new ES6 and ES7 features.
A: let, count fast scope; Deconstruction, extracting values from objects and arrays; Arrow function; String template; Extended operators… ; Short for object; The module; Promise (async); The class; Extensions to native objects (with many new methods); The for – (Object. The keys and values, entries, etc.); Symbal (); Uncommonly used proxy, reflect, generate
10. What is a Promise object and how to use it?
A: Promise is the STANDARD ES syntax for asynchronous callbacks, often used to address issues such as asynchronous nesting and multiple asynchronous callbacks completing simultaneously. A Promise is a constructor, which is like a container that wraps asynchronous code inside it. The Promise has three states (pending, fulfilled and Rejected) initialized as pending. When the asynchronous request succeeds, call resolve with the status from Pending — > depressing. When the asynchronous request fails, call Reject with the status from Pending — > Rejected. The state is irreversible. Disadvantages: cumbersome to write, unable to implement asynchronous code, synchronous execution requirements (with async functions can be used)
11. What is cross-domain and what are the common ways to solve cross-domain?
A: Cross-domain is a browser-side behavior. According to the same origin policy, if the requested protocol, domain name, or port has only one difference, the browser will cross domain. Cross-domain is a mechanism that exists for security, and the browser will delete the data in the cross-domain request, causing peer errors. In practical development, cross-domain situations will inevitably occur. Solutions usually include: 1.JSONP technology, which uses the SRC attribute of script without cross-domain restrictions; 2. Background configuration, or the next browser plug-in. 3. Background agent (Node) 4.Iframe domain enhancement (rarely)
12, what is the function of anti-shake, throttling, and handwritten basic code
A: The purpose of anti-shake and throttling is to improve operation efficiency and reduce the number of times the function is executed. Stabilization: Combine multiple function executions into one execution
Function debounce(fn,delay){function debounce(fn,delay){var timer = null; return function(){ var args = arguments; var that = this; if(timer) clearTimeout(timer) timer = setTimeout(function(){ fn.apply(that,[...arguments]) },delay) } } 123456789101112Copy the code
Throttling: Specifies a unit of time within which an event callback is triggered. If the interval is exceeded, it is executed. Otherwise, it is not executed.
function throttle(fn,gapTime){ let _lastTime = null; return function(){ var that = this; var args = arguments; let _nowTime = + new Date(); if(_nowTime-_lastTime > gapTime || ! _lastTime){ fn.apply(that,args); _lastTime = _nowTime; }}} 123456789101112Copy the code
13. What Event Loop?
A: Js is blocking the single-threaded language, js produces in the process of execution execution environment, the order of execution environment will be added to the execution stack, when faced with asynchronous tasks, will be added to the task queue, synchronization stack, stack when synchronization execution after the event loop from asynchronous task queue of extraction in the code to be executed on the execution stack. This process is called an event loop. So JS is asynchronous or synchronous.
console.log('script start') setTimeout(function() { console.log('setTimeout') }, 0) new Promise(resolve => { console.log('Promise') resolve() }) .then(function() { console.log('promise1') }) Then (function() {console.log('promise2')}) console.log('script end') 12345678910111213141516171819Copy the code
15. Do you know about front-end safety? What are XSS attacks and CSRF cross-site request forgery? How to prevent it?
A: Front-end security issues, in the process of work will pay attention to these issues. 1, XSS code injection problems, usually do not trust user input, escape the input and output content () encodeURIComponent), brackets Angle brackets, etc. Leverage the user’s trust in the site
CSRF cross-site request forgery is a kind of hijacking the user in the current login of the Web application to perform an unintended attack: using the user login state to initiate malicious request website to the user's trustCopy the code
Add verification code (slightly worse experience), do not let the third party access cookie set the cookie samesite, request authentication plus token,
3. Password problem: Encrypt the password (MD5, etc.)
16. How to deal with the loss of accuracy?
A: Why: JS uses the Number type to represent a Number, which is 64 bits.
The computer first converts base 10 to base 2, and 0.1 and 0.2 go through an infinite loop as they convert to binary. Since there is a limit of 51 bits, the surplus is cut off, so switching between bases loses accuracy. It is usually possible to multiply a decimal number into a positive integer and then reverse it. ParseFloat ((0.1 + 0.2) toFixed (10))
16. What are the common ways in which the front-end requests data? Tell the differences.
A: Front-end network request common form, Ajax, fetch common library file Jquery or AXIos.
The Form submission data page will refresh and the user experience will be poor. Ajax is a comprehensive technology that enables asynchronous updating of page content. Easy to use, usually using JQ encapsulation, with additional JS loading costs. Fetch is a new API and relatively low-level. At present, there are many compatibility problems in browsers. For example, the old version does not carry cookies, cannot directly pass JS objects as parameters, and does not support JSONP, etc. 123Copy the code
17. How do I check that an object must be an array?
Answer: 1, the Object. The prototype. ToString. Call (), the premise is the toString method without being rewritten. 2. The internal mechanism of instanceof is to determine whether the prototype of the type can be found in the prototype chain of the object. [] instanceof Object; // true 3. Array.isarray () Is a new method in ES5 that is slightly less compatible.
18. Does JS loading block page rendering? If so, how to solve it?
A: will defer: download in parallel and execute after the page has been parsed, in script order. (Common) Async: Asynchronously downloads code and executes the code after the download is complete without following the script order of the page.
20. What are common front-end performance optimizations? Answer: 1: load optimization
CDN, file compression obfuscated merge, load on demand (asynchronous components), front-end caching, browser caching (cache-control,exprices) DNS pre-resolution, server rendering nuxt, Next (SEO), image lazy loadingCopy the code
2: Script optimization
Reduce merging DOM operations (createDocumentFragment), CSS3 instead of JS animations, caching variables, using requestAnimationFrame proxy setTimeout, reducing reflow and Repain, event proxy, Enable GPU rendering tranfrom:translateX(0) 1Copy the code
3: Picture optimization
Sprite image (reduced request), using SVG and Iconfont (font image) instead of image, image compression 1Copy the code
For more video tutorials on front-end interview and performance optimization and front-end automated testing, please email or click here.