[Recommended collection] 2020 Dachang JavaScript Interview Questions are being updated continuously~

1. Talk about a few basic specifications for writing JavaScript

Do not declare multiple variables on the same line
, please use =/!To compare true/false or numeric values,
use object literals instead of new Array.
Do not use global functions.
Switch statements must have default branches.
If statements must use curly braces
. Variables in for-in loops should use the let keyword to clearly define the scope. To avoid scope pollution

2. Closures that cannot be bypassed

A closure is a function that can read the internal variables of other functions. A
closure is a function that has access to variables in the scope of another function. The most common way to create a closure is
to create another function within one function and pass another function. The function accesses the local variables of this function, and the use of closures can break through the scope of scope
. The characteristics of closures:

Functions are nested inside functions.
Internal functions can refer to outer parameters and variables.
Parameters and variables will not be recycled by the garbage collection mechanism.

Advantages: encapsulation and caching can be realized.
Disadvantages: memory consumption, improper use will cause memory overflow.
Solution: Before exiting the function, delete all the unused local variables

3. Tell me about your understanding of the scope chain

The role of the scope chain is to ensure that the variables and functions that have been accessed in the execution environment are in order. Variables in the scope chain can only be accessed upwards, and the variable access to the window object will be terminated. The scope chain downward access to the variables is not Allowed.
Simply put, the scope is the accessible scope of variables and functions, that is, the scope controls the visibility and life cycle of variables and functions

4. JavaScript prototype, prototype chain? What are the characteristics?

Every object initializes a property in its interior, which is prototype. When we access the property of an object, if the property does not exist in the object, then he will go to the prototype to find the property, and the prototype will It has its own prototype, so I just keep looking for it, which is the concept of the prototype chain we usually call.
Relationship: instance.constructor.prototype = instance. proto
features: JavaScript objects are passed by reference, and every one we create The new object entity does not have a copy of its own prototype. When we modify the prototype, the objects related to it will also inherit this change. When we need a property, the Javascript engine will first check whether there is this property in the current object, and if it doesn’t, it will look for its prototype object. With this attribute, the recursion continues until the built-in Object object is retrieved

5. How does Javascript implement inheritance?

  • Constructive inheritance
  • Prototype inheritance
  • Instance inheritance
  • Copy and inherit the
    prototype mechanism or apply and call methods to achieve simpler, it is recommended to use a mixed method of constructor and prototype
function Parent(){
this.name = 'wang';
}
function Child(){
 this.age = 28;
}
Child.prototype = new Parent();//继承了Parent,通过原型
var demo = new Child();
alert(demo.age);
alert(demo.name);//得到被继承的属性

6. The garbage collection mechanism in JS

Necessity: Since strings, objects, and arrays have no fixed size, only when their size is known can they be dynamically allocated. Every time a JavaScript program creates a string, array, or object, the interpreter must allocate memory to store that entity. As long as the memory is dynamically allocated like this, the memory must eventually be released so that they can be reused. Otherwise, the JavaScript interpreter will consume all available memory in the system and cause the system to crash.

This passage explains why the system needs garbage collection. Unlike C/C++, JS has its own set of garbage collection mechanism (Garbage Collection). The JavaScript interpreter can detect when the program no longer uses an object. When he determines that an object is useless, he knows that the object is no longer needed and can release the memory it occupied. E.g:

var a="hello world";
var b="world";
var a=b;
//这时,会释放掉"hello world",释放内存以便再引用

Methods of garbage collection: mark removal, count reference.

Mark clear

This is the most common way of garbage collection. When a variable enters the environment, it is marked as "enter environment". Logically speaking, the memory occupied by the variables entering the environment can never be released, and the memory occupied by the environment variables can never be released. As long as the execution process enters the corresponding environment, they may be used. When leaving the environment, it is marked as leaving the environment.

When the garbage collector runs, it will mark all the variables stored in the memory (add all), and then remove the variables in the environment variables and the variables referenced by the variables in the environment variables (conditional removal of the mark) , Delete all marked variables. The deleted variables cannot be accessed in the environment variables, so they will be deleted. Finally, the garbage collector completes the memory cleanup and reclaims the memory they occupy.

Reference counting

Another less common method is the reference counting method. The reference counting method means the number of times that each value is not referenced. When a variable is declared and assigned to the variable with a reference type value, the number of times the value is referenced On the contrary, if the variable that contains the reference to this value gets another value, the number of references to the original reference value is reduced by 1. When the number of references to this value is 0, it means that there is no way to access it again This value is set, so the occupied memory is reclaimed so that when the garbage collector runs again, these values ​​with 0 references will be released.

There will be memory leaks with reference counting, let's look at the reasons below:

function problem() {
var objA = new Object();
var objB = new Object();
objA.someOtherObject = objB;
objB.anotherObject = objA;
}

In this example, objA and objB refer to each other through their respective attributes. In this case, the number of references of the two objects is 2. In the strategy of using reference counting, after the function is executed, the two objects are out of scope. , After the function execution is completed, because the count is not 0, such mutual references will cause memory leaks if they exist in large numbers.

Especially in DOM objects, this kind of problem is also prone to:

var element=document.getElementById(’‘);
var myObj=new Object();
myObj.element=element;
element.someObject=myObj;

In this way, there will be no garbage collection process.

7. Function Currying

In a function, the technique of filling a few parameters first, and then returning a new function is called the currying of the function. Generally, it can be used to preset common parameters for the function without intruding into the function for multiple repeated calls.

const add = function add(x) {
	return function (y) {
		return x + y
	}
}
const add1 = add(1)
add1(2) === 3
add1(20) === 21

8.js anti-shake

Debouncing

The anti-shake technology can combine multiple sequential calls into one time, that is, the number of times the event is triggered within a certain period of time.
In layman's terms, take a look at this simplified example:

// 简单的防抖动函数
function debounce(func, wait, immediate) {
    // 定时器变量
    var timeout;
    return function() {
        // 每次触发 scroll handler 时先清除定时器
        clearTimeout(timeout);
        // 指定 xx ms 后触发真正想进行的操作 handler
        timeout = setTimeout(func, wait);
    };
};
 
// 实际想绑定在 scroll 事件上的 handler
function realFunc(){
    console.log("Success");
}
 
// 采用了防抖动
window.addEventListener('scroll',debounce(realFunc,500));
// 没采用防抖动
window.addEventListener('scroll',realFunc);

The above simple anti-shake example can be tested in a browser. The approximate function is that if the scroll event is not triggered twice within 500ms, then the function we really want to trigger in the scroll event will be triggered.

The above example can be better encapsulated

// 防抖动函数
function debounce(func, wait, immediate) {
    var timeout;
    return function() {
        var context = this, args = arguments;
        var later = function() {
            timeout = null;
            if (!immediate) func.apply(context, args);
        };
        var callNow = immediate && !timeout;
        clearTimeout(timeout);
        timeout = setTimeout(later, wait);
        if (callNow) func.apply(context, args);
    };
};
 
var myEfficientFn = debounce(function() {
    // 滚动中的真正的操作
}, 250);
 
// 绑定监听
window.addEventListener('resize', myEfficientFn);

9.js throttling

The anti-shake function is really good, but there are also problems, such as lazy loading of pictures. I hope that the pictures will be continuously loaded during the sliding process, not only when I stop sliding. Or the ajax request loading of the data when it is falling is the same.

At this time, we hope that even if the page is constantly being scrolled, the scroll handler can be triggered at a certain frequency (for example, once every 250ms). For this type of scenario, another technique is used, called the throttling function. ).

Throttling function, only allows a function to be executed once in X milliseconds.

Compared with anti-shake, the main difference of the throttling function is that it guarantees that the event handler we want to trigger will be executed at least once within X milliseconds.
Compared with anti-shake, the throttling function has one more mustRun attribute, which means that the handler will be triggered once within milliseconds of mustRun. The timer is also used. Take a look at a simple example:

// 简单的节流函数
function throttle(func, wait, mustRun) {
    var timeout,
        startTime = new Date();
 
    return function() {
        var context = this,
            args = arguments,
            curTime = new Date();
 
        clearTimeout(timeout);
        // 如果达到了规定的触发时间间隔,触发 handler
        if(curTime - startTime >= mustRun){
            func.apply(context,args);
            startTime = curTime;
        // 没达到触发间隔,重新设定定时器
        }else{
            timeout = setTimeout(func, wait);
        }
    };
};
// 实际想绑定在 scroll 事件上的 handler
function realFunc(){
    console.log("Success");
}
// 采用了节流函数
window.addEventListener('scroll',throttle(realFunc,500,1000));

The example of the above simple throttling function can be tested in a browser. The general function is that if the interval of scroll triggering is always shorter than 500ms within a period of time, then it can be guaranteed that the event handler we hope to call will be triggered at least once within 1000ms .

10. Talk about Commonjs, AMD and CMD

A module is a file that can implement a specific function. With a module, you can easily use other people's code, and you can load any module for any function you want.

Commonjs: Started from server-side modularization, synchronously defined modularization, each module is a separate scope, module output, modules.exports, module loading require() to import modules.

AMD: The meaning of the Chinese name asynchronous module definition.

requireJS implements the AMD specification and is mainly used to solve the following two problems.

1. Multiple files have dependencies, and the dependent file needs to be loaded into the browser earlier than the file that depends on it.
2. The browser will stop page rendering when loading. The more files are loaded, the longer the page will lose response time.
Syntax: requireJS defines a function define, which is a global variable used to define a module.

Examples of requireJS:

//定义模块
define(['dependency'], function(){
var name = 'Byron';
function printName(){
console.log(name);
}
return {
printName: printName
};
});
//加载模块
require(['myModule'], function (my){
my.printName();
}

requirejs defines a function define, which is a global variable used to define modules:
define(id?dependencies?,factory)

Use the module loading function on the page:
require([dependencies],factory);

Summarizing the AMD specification: the require() function is loaded asynchronously when loading dependent functions, so that the browser will not lose response, and the callback function it specifies will only be executed if the previous module is successfully loaded.

Because the web page will stop rendering when loading js, we can load js asynchronously, and if we need to rely on something, we also need to rely on it asynchronously, and then execute some methods after dependency.

Due to limited space, only part of the interview questions can be shared, and more interview questions and answers can be read and downloaded by [click me] ~ Share it with everyone for free, it is a thankful feedback.

11. Please explain what is event delegation/event delegation

Event delegation (Event Delegation), also known as event delegation. It is a common technique for binding events commonly used in JavaScript. As the name implies, "event agent" is to delegate the event that originally needed to be bound to the parent element, and let the parent element take on the role of event monitoring. The principle of event delegation is the bubbling of events of DOM elements. The advantage of using event proxy is that it can improve performance,
save a lot of memory, and reduce event registration. For example, it is great to proxy all td click events on the table. It is
possible to realize that there is no need to bind to it again when adding new sub-objects.

12. Event model

The occurrence of events defined in W3C goes through three stages: capturing stage (capturing), target stage
(targetin), bubbling stage (bubbling)

Bubbling event: When you use event bubbling, the child element is triggered first, and then the parent element is triggered.
Capture type event: When you use event capture, the parent element is triggered first, and the child element triggers the
DOM event flow: Two event models are supported at the same time: capture event and bubbling event.
Stop bubbling: In W3c, use the stopPropagation() method; set cancelBubble = true under IE to
prevent capture: the default behavior of preventing events, such as click-a Jump. In W3c, use the preventDefault() method and set window.event.returnValue = false under IE

13.What exactly does the new operator do?

Create an empty object, and the this variable refers to the object, and at the same time inherits the prototype of the function. The
properties and methods are added to the object referenced
by this . The newly created object is referenced by this, and finally returns this implicitly.

14. Ajax principle

The principle of Ajax is simply to add an intermediate layer (AJAX engine) between the user and the server, through the XmlHttpRequest object to send asynchronous requests to the server, obtain data from the server, and then use javascript to manipulate the DOM to update the page. Make user operations and server responses asynchronous. The most critical step is that the
Ajax process of obtaining request data from the server only involves JavaScript, XMLHttpRequest and DOM. XMLHttpRequest is the core mechanism of Ajax

15. Simple implementation of object deep cloning

function deepClone(obj){
var newObj= obj instanceof Array ? []:{};
for(var item in obj){
var temple= typeof obj[item] == 'object' ? deepClone(obj[item]):obj[item];
newObj[item] = temple;
}
return newObj;
}

ES5 is a common method of object cloning. Note that an array is an object, but it is different from an object, so we judged some types at the beginning and decided whether newObj is an object or an array~

16. Encapsulate the native ajax into a promise

var  myNewAjax=function(url){
return new Promise(function(resolve,reject){
var xhr = new XMLHttpRequest();
xhr.open('get',url);
xhr.send(data);
xhr.onreadystatechange=function(){
if(xhr.status==200&&readyState==4){
var json=JSON.parse(xhr.responseText);
resolve(json)
}else if(xhr.readyState==4&&xhr.status!=200){
reject('error');
}
}
})
}

17. To implement an once function, the incoming function parameters are only executed once

function ones(func){
var tag=true;
return function(){
if(tag==true){
func.apply(null,arguments);
tag=false;
}
return undefined
}
}

18.js monitor the changes of object properties

Let's assume there is a user object here,

(1) In ES5, you can use Object.defineProperty to monitor existing properties

Object.defineProperty(user,'name',{
set:function(key,value){
}
})

Disadvantages: If the id is not in the user object, you cannot monitor the change of the id
(2) It can be achieved through Proxy in ES6

var  user = new Proxy({},{
set:function(target,key,value,receiver){
}
})

In this way, even if there is an attribute that does not exist in the user, it can be defined by user.id to monitor the change of this attribute in this way~

19. How to achieve the effect of sleep (es5 or es6)

(1) The way of the while loop

function sleep(ms){
var start=Date.now(),expire=start+ms;
while(Date.now()<expire);
console.log('1111');
return;
}

After executing sleep(1000), 1111 is output after sleeping for 1000ms. The shortcomings of the above loop method are obvious, and it is easy to cause an endless loop.

(2) Realize through promise

function sleep(ms){
var temple=new Promise(
(resolve)=>{
console.log(111);setTimeout(resolve,ms)
});
return temple
}
sleep(500).then(function(){
//console.log(222)
})
//先输出了111,延迟500ms后输出222

(3) Encapsulation through async

function sleep(ms){
return new Promise((resolve)=>setTimeout(resolve,ms));
}
async function test(){
var temple=await sleep(1000);
console.log(1111)
return temple
}
test();
//延迟1000ms输出了1111

(4). Realized by generate

function* sleep(ms){
yield new Promise(function(resolve,reject){
console.log(111);
setTimeout(resolve,ms);
})
}
sleep(500).next().value.then(function(){console.log(2222)})

20. What is Function. proto (getPrototypeOf)?

Get the prototype of an object, in the form of _proto_ in chrome, or in the form of Object.getPrototypeOf in ES6.
So what is Function.proto? In other words, from what object the Function inherits, let's make the following judgments.
Function. proto == Object.prototype //false
Function. proto == Function.prototype//true
We found that the prototype of Function is also Function.

Due to limited space, only part of the interview questions can be shared, and more interview questions and answers can be read and downloaded by [click me] ~ Share it with everyone for free, it is a thankful feedback.

21. How to solve cross-domain problems?

First, understand the browser’s same origin policy. The same origin policy/SOP (Same origin policy) is a convention. It was introduced by Netscape in 1995. It is the core and most basic security function of the browser. Source strategy, the browser is vulnerable to XSS, CSFR and other attacks. The so-called homology refers to the same "protocol + domain name + port", even if two different domain names point to the same ip address, they are not homologous

  • Cross-domain via jsonp
var script = document.createElement('script');
script.type = 'text/javascript';
// 传参并指定回调执行函数为onBack
script.src = 'http://www.....:8080/login?user=admin&callback=onBack';
document.head.appendChild(script);
// 回调执行函数
function onBack(res) {
 alert(JSON.stringify(res));
}
  • document.domain + iframe cross domain
//父窗口:(http://www.domain.com/a.html)
<iframe id="iframe" src="http://child.domain.com/b.html"></iframe>
<script>
 document.domain = 'domain.com';
 var user = 'admin';
</script>

//子窗口:(http://child.domain.com/b.html)
document.domain = 'domain.com';
// 获取父窗口中变量
alert('get js data from parent ---> ' + window.parent.user);
  • Nginx proxy cross-domain
  • nodejs middleware proxy cross-domain
  • The backend sets the secure domain name in the header information

22. Introduce what built-in objects js has

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

23. What are the methods of JS to define objects

Object literal: var obj = {};
Constructor: var obj = new Object();
Object.create(): var obj = Object.create(Object.prototype);

24. What do you think are good places to write the jQuery source code?

  • The jquery source code is encapsulated in the self-executing environment of an anonymous function, which helps prevent global pollution of variables. Then, by passing in the window object parameter, the window object can be used as a local variable. The advantage is that when the window object is accessed in jquery, There is no need to return the scope chain to the top-level scope, so that the window object can be accessed faster. Similarly, passing in the undefined parameter can shorten the scope chain when looking for undefined

  • Jquery encapsulates some prototype properties and methods in jquery.prototype. In order to shorten the name, they are assigned to jquery.fn. This is a very vivid way of writing

  • There are some methods of arrays or objects that are often used. jQuery saves them as local variables to improve access speed

  • The chain call implemented by jquery can save code, all returned are the same object, which can improve code efficiency

25. How to judge an array through JS

  • The instanceof operator is used to test whether an object is the property of the prototype constructor in its prototype chain
var arr = [];
arr instanceof Array; // true
  • isArray
Array.isArray([]) //true
Array.isArray(1) //false
  • The constructor property returns a reference to the array function that created this object, that is, returns the constructor function corresponding to the object
var arr = [];
arr.constructor == Array; //true
  • Object.prototype
Object.prototype.toString.call([]) == '[object Array]'
// 写个方法
var isType = function (obj) {
 return Object.prototype.toString.call(obj).slice(8,-1);
 //return Object.prototype.toString.apply([obj]).slice(8,-1);
}
isType([])  //Array

Guess you like

Origin blog.csdn.net/hugo233/article/details/112547887