Currently looking for a job, so the parties collected a bunch of interview questions. In fact, the process of brushing interview questions can also update your knowledge, so it also reminds you to read and understand more. If you have a better understanding of the following topics, we will update them in real time. New topics will be updated from time to time. Hope to help some friends ~
A variety of function method definition and difference
1. Typeof operator and instanceof operator and isPrototypeOf() method differences
Typeof is an operator used to detect data types such as null, undefined, String, number, and Boolean, and reference data types such as Object and function. However, for reference data types such as regular expressions, dates, and arrays, It recognizes all objects; Instanceof is also an operator that does a good job of identifying which reference type the data is. It differs from isPrototypeOf in that it checks whether the constructor’s prototype exists in the specified object’s prototype chain; IsPrototypeOf is used to check if the object calling this method exists in the prototype chain of the specified object, so it is essentially checking for different targets.
2. Differences between call() and apply()
In fact, the functions of Apply and Call are the same, except that the argument lists passed in are different. Apply: Can take a maximum of two arguments — a new this object and an array argArray.
Reference: www.cnblogs.com/lengyuehuah…
What does the global function eval() do?
Eval () has only one argument, and if the argument passed is not a string, it returns it directly. If the argument is a string, it compiles the string as if it were javascript code. If the compilation fails, a syntaxError is thrown. If the compilation is successful, the code starts executing and returns the value of the last expression or statement in the string, or undefined if the last expression or statement has no value. If the string throws an exception, the exception passes the call to Eval ().
4. Describe the differences between the following variables: null, undefined, or undeclared
Null means “no object”, that is, there should be no value, and is 0 when converted to a value. Typical usage:
(1) as the parameter of the function, indicating that the parameter of the function is not an object.
(2) as the end of the object prototype chain.
Undefined means “missing value”, that is, there should be a value here, but it is not defined yet, and when converted to a value, NaN. Typical usage:
(1) If a variable is declared but not assigned, it is undefined.
(2) When the function is called, the argument that should be provided is not provided, which is equal to undefined.
(3) The object has no assigned attribute. The value of this attribute is undefined.
(4) If the function does not return a value, undefined is returned by default.
Undeclared: javascript syntax error, used directly without declaring, js cannot find the corresponding context.
5. What’s the difference between == and ==?
=== = equality == equality ==, if the two values have different types, type conversion should be performed before comparison. ===, do not do type conversion, different types must vary.
Let’s start with lambda = lambda = lambda, which is a little bit easier. The following rule is used to determine if two values are equal:
If both are numeric and have the same value, then equal. (! The exception is if at least one of them is a NaN, then [not equal]. (The only way to determine whether a value is a NaN is to use isNaN().) If both are strings and the characters are the same in each position, then [equal]; Otherwise [unequal]. If both values are true, or both are false, then [equal]. If both values refer to the same object or function, then [equal]; Otherwise [unequal]. If both values are null, or both are undefined, then [equal].Copy the code
If two values are of the same type, compare ===. If two value types are different, they may be equal. Use the following rules to cast and compare:
If one is null and one is undefined, then [equal]. If one is a string and one is a number, convert the string to a number and compare. If either value is true, convert it to 1 and compare; If either value is false, convert it to 0 and compare. If one is an object and the other is a number or string, convert the object to a value of the underlying type and compare. The object is converted to the base type using its toString or valueOf methods. The js core built-in class will try valueOf before toString; The exception is Date, which utilizes the toString conversion. Objects that are not core to JS are not equal to any other combination.Copy the code
6. Synchronous and asynchronous?
1. Process synchronization: when a function call is made, it does not return until the result is received. 2. Asynchrony is the opposite of synchronization. When an asynchronous procedure call is made, the caller does not get the result immediately. The part that actually handles the call notifies the caller through status, notifications, and callbacks after completion.
Ii. Various concepts/principles
1. What is event broker/event delegate?
Event broker/event delegate takes advantage of the event bubble feature to bind events that should be bound to multiple elements to their ancestor elements. Especially when dynamically adding child elements, it is very convenient to improve program performance and reduce memory space.
2. What is event bubbling? What is event capture?
Bubbling events: Events fire in order from the most specific event target to the least specific event target (the Document object).
Captured events: Events fire from the least precise object (the Document object) to the most precise (events can also be captured at the window level, though they must be specified by the developer).
Browsers that support the W3C standard use the addEventListener(event,fn,useCapture) method to add events. The third argument in the base,useCapture, is a Boolean value that sets whether the event is executed when the event is captured or when the event bubbles. The attachEvent() method is not set, but the IE event model is executed by default when the event bubbles, that is, when useCapture is false. So setting useCapture to false when handling events is safer and browser-compatible.
3. How do I stop bubbles?
The W3C method is e.topPropagation (), IE uses e.ancelbubble = true. For example: Windows. The event? window.event.cancelBubble = true : e.stopPropagation();
Return False also prevents bubbling.
4. How do I prevent default events?
W3c uses e.preventDefault(), IE uses e.returnValue = false, for example:
functionStopDefault (e) {// Block default browser actions (W3C)if( e && e.preventDefault ) e.preventDefault(); // Block the default action of the function in IEelse
window.event.returnValue = false;
}
Copy the code
Return false also prevents default behavior.
5. Briefly describe the orientation of this in javascript
The first rule is that this always refers to the object on which the function was run, not the object on which the function was created.
- Normal function calls, this is whoever the function is called by.
- Constructor, if called directly without the new operator, this refers to the window. After an object instance is generated using the new operator, this points to the newly generated object.
- Anonymous functions or functions that are not in any object point to the window.
- If it is call, apply, etc., whoever this is specified is the same.
- Reference: www.cnblogs.com/beidan/p/53…
5. Native objects and host objects
Native objects are ECMAScript objects. All built-in objects are native, such as Array, Date, RegExp, etc.
Host objects are objects specified by the host environment, such as the browser, to complete the ECMAScript implementation environment, such as Document, Location, Navigator, etc.
6. Base and reference data types
Basic data types refer to simple data segments. There are five types, including NULL, undefined, String, Boolean, and number.
Reference data types refer to objects with multiple values, including Object, array, date, regEXP, function, and so on.
Main differences:
- Different memory allocation when declaring variables: the former occupies a fixed and small amount of space and is stored in the stack, that is, the location of the variable access; The latter is stored in the heap, and what the variable accesses is actually a pointer to the memory address where the object is stored.
- And because memory allocation is different, variables are copied differently. After the former is copied, the two variables are independent, because the value is copied; The latter is a copy of a pointer, the two variables point to the value of the pointer to the content, once one side changes, the other side will also be affected.
- Arguments are passed differently: Although arguments to a function are passed by value, the reference value is passed by a memory address, and the argument and parameter refer to the same object, so changes to this parameter inside the function are reflected outside the function. The original value simply passes the value of the variable to the parameter, which then has no effect on the variable.
7. Deep and shallow copies
The difference between www.cnblogs.com/echolun/p/7…
The method of deep copy www.cnblogs.com/Mrrabbit/p/…
Explain how archetypal inheritance works
Reference: www.cnblogs.com/syfwhu/p/44…
9. Explain why this next line of code is not IIFE:
function foo(){
//code
}()
Copy the code
Statements beginning with the function keyword are parsed into function declarations, which are not allowed to run directly. Only if the parser parses this statement as a function expression can it be run directly. Start with an operator.
(function foo(){ // code.. }) ()Copy the code
Explain how AJAX works in as much detail as possible
Ajax simply means making an asynchronous request to the server via an XmlHttpRequest object, retrieving data from the server, and then using javascript to manipulate the DOM to update the page.
The advantages of ajax
- The biggest point is that there is no page refresh, in the page and the server communication, to the user experience is very good.
- Asynchronous communication with the server enables rapid response without interrupting user operations.
- Some of the previous server burden can be transferred to the client, using the client’s idle capacity to deal with, reduce the burden of the server and bandwidth, save space and broadband rental costs, the principle of Ajax is “data on demand”, can reduce redundant requests to the greatest extent.
- Based on standardized and widely supported technologies, no need to download plug-ins or applets.
The disadvantage of ajax
- Ajax breaks the browser’s back mechanism, meaning that the user can’t go back to the previous page through the browser’s back button. While some browsers solve this problem, such as Gmail, it doesn’t change the mechanics of Ajax, which can be very expensive to develop and is incompatible with the rapid development required by Ajax frameworks. This is a very serious problem with Ajax.
- Security issues. Technology is also bringing new security threats to IT enterprises, as Ajax technologies create a direct channel to enterprise data. This leaves developers inadvertently exposing more data and server logic than ever before.
- Search engine support is weak.
- Broke the exception mechanism of the program. At least for now, Ajax frameworks like Ajax.dll and Ajaxpro.dll break the exception mechanism. I have encountered this problem in the development process, but I checked the Internet and found very little information about it. Later, I did my own experiment, using Ajax and traditional form submission modes to delete a piece of data… It brought great difficulties to our debugging.
- In addition, there are problems with other aspects, such as defeating the purpose of URLS and resource positioning. For example, if I give you a URL and I use Ajax, maybe what you see under that URL is different from what I see under that URL. This is contrary to the original intention of resource positioning.
- Some handheld devices (such as mobile phones, PDAs, etc.) do not support Ajax well at present. For example, when we open ajax websites on mobile browsers, they do not support Ajax at present. Of course, this problem has nothing to do with us.
What’s the difference between GET and POST?
In fact, there is no difference between GET and POST at all. They are all request methods in the HTTP protocol. The underlying implementation is based on TCP/IP protocol. So-called distinction, just the browser manufacturer according to the agreement, do limit it.
- Get sends data requests in plaintext, while POST sends data requests in ciphertext.
- Get transfers a limited amount of data because the URL length is limited, whereas POST does not.
- The parameters of a GET request can only be ASCII, so Chinese requires URL encoding, while the parameters of a POST request do not have this restriction
- GET generates a TCP packet; POST generates two TCP packets. For GET requests, the browser sends both HTTP headers and data, and the server responds with 200 (return data). For POST, the browser sends a header, the server responds with 100 continue, the browser sends data, and the server responds with 200 OK (returns data).
- Reference: www.cnblogs.com/logsharing/…
12. Please explain the variable declaration upgrade
Variables declared through var are promoted to the top of the scope. Not only variables, but function declarations are also promoted. When both variable and function declarations are promoted in the same scope, the variable still precedes the function.
Reference: www.cnblogs.com/guanhuachen…
13. Please point out the difference between document.onload and document.ready
There are two types of events when a page is loaded. One is ready, indicating that the document structure is loaded (excluding non-text media files such as images), and the other is onload, indicating that all elements of the page, including images, are loaded.
14. How do I get query string parameters from the browser URL?
getUrlParam : function(name){
//baidu.com/product/list?keyword=XXX&page=1
var reg = new RegExp('(^ | &)' + name + '= (/ ^ & *) (& | $)');
var result = window.location.search.substr(1).match(reg);
return result ? decodeURIComponent(result[2]) : null;
}
Copy the code
- First, set up a function and pass it a parameter, the key of the SEARCH part of the URL.
- Sets a regular expression that starts with & or none, takes arguments in the middle, and ends with # or & or none.
- Through the window. The location. The search. The substr (1) the match () match, returns an array
- If the array is not empty, return the third value of the array, which is the second substring of the regular expression
15. What is a ternary expression? What does “three yuan” mean?
Ternary expressions:? :. Ternary – three operation objects.
In the expression Boolean -exp? Value0: In value1, “value0” is evaluated if the result of the “Boolean expression” is true, and the result is the final value produced by the operator. If the result of the “Boolean expression” is false, “value1” is evaluated, and again, its result becomes the final value produced by the operator.
16. What exactly is arguments in JavaScript?
Arguments: javascript every function has an instance of Arguments, which references the Arguments to the function. You can use array subscripts to refer to the Arguments element as “[]”. Arguments. length is the number of arguments to the function, and arguments.callee refers to the function itself.
In function code, with special object arguments, the developer does not need to specify the argument name, but can access the corresponding argument by using subscripts.
function test() {
var s = "";
for (var i = 0; i < arguments.length; i++) {
alert(arguments[i]);
s += arguments[i] + ",";
}
return s;
}
test("name"."age"); //name,ageCopy the code
Arguments has some array properties, but is not really an array, just an array-like object. It doesn’t have many of the methods of an array and can’t call.jion(),.concat(),.pop(), etc., like a real array.
17. What is “use strict”; ? What are the advantages and disadvantages of using it?
Expression appears in code -“use strict”; This means that code is parsed according to a strict pattern, which makes Javascript run under stricter conditions.
Benefits:
- Eliminate some unreasonable and inaccurate Javascript syntax, reduce some weird behavior;
- Eliminate some unsafe code operation, to ensure the safety of code operation;
- Improve the efficiency of the compiler, increase the running speed;
- Set the stage for future versions of Javascript.
The bad:
- The same code may run differently in “strict mode”;
- Some statements that work in “normal mode” will not work in “strict mode”.
18. Explain JavaScript’s same-origin policy
The same origin policy means that two pages that have the same protocol, port (if specified), and host (domain name) belong to the same source. However, in IE, the port number is not added to the condition of homology. Therefore, the item with different ports in the figure above is considered homology in IE. In the < script > < img > < iframe > SRC, href links can be arbitrary network resources, it is not follow tongyuan strategy.
19. Explain how JSONP works and why it is not true AJAX.
JSONP (JSON with Padding) is a simple and efficient way to cross domains. Script tags in HTML can load and execute javascript from other domains, so we can use script tags to dynamically load resources from other domains. For example, if I want to load the data of domain B from the page pageA of domain A, then IN the page pageB of domain B, I declare the data required by pageA in the form of JavaScript, and then load the pageB with script tags in pageA, then the script in pageB will be executed. JSONP added a callback function on this basis. After pageB is loaded, the function defined in pageA will be executed, and the required data will be passed to the function in the form of parameters. JSONP is easy to implement, but there are security risks. If a third-party script is executed haphazard, it can tamper with page content and intercept sensitive data. But JSONP is a good choice for passing data between trusted parties.
AJAX is not cross-domain, JSONP is cross-domain, and the way they receive parameters is different!
20. What changes happen inside the constructor when you create an object from new?
function Person(){}
Person.prototype.friend = [];
Person.prototype.name = ' ';
var a = new Person();
a.friend[0] = 'wang'; var b = new Person(); console.log(b.friend); //Array ["Wang" ]
Copy the code
- Creates an empty object, and the this variable references the object and inherits the prototype of the function.
- Properties and methods are added to the object referenced by this.
- The newly created object is referred to by this and implicitly returns this.
22. What is cross-domain? What is the solution to cross-domain problems?
Cross-domain is understood based on the same origin policy of the browser. This policy means that the requests must be from the same port, protocol, and domain name. Client scripts from different sources cannot read and write resources from each other without explicit authorization.
Due to the browser’s same-origin policy, scripts that are not same-origin cannot operate on objects under other sources. To manipulate objects from another source, you need to cross domains.
Solution: JSONP
23. What is a prototype?
The function traces the prototype object through prototype, and the object traces the prototype object through _proto_.
If you want to add a method to multiple instances created by a constructor, it is not a wise choice to add a method to each instance. This is where the prototype comes in.
Add a method to the stereotype of the instance, and all instances of the stereotype have the method.
Prototype chain inheritance:
function Show(){
this.name="run";
}
function Run(){
this.age="20"; } run.prototype =new Show(); var show=new Run(); Alert (show.name)// Result: runCopy the code
24. What is a closure? What are the usage scenarios?
A closure is a function that can read internal variables of other functions. It is usually created when a function is nested. It is useful for reading internal variables of functions and for keeping the values of these variables in memory and not being automatically cleared after external function calls.
25. Have you heard about Promise? What does callback hell have to do with it?
www.liaoxuefeng.com/wiki/001434…
Three, the timer thing ~ (partial white logic)
1. If the user keeps clicking a button, how can the request be submitted only once without affecting subsequent use? (in fact, how to throttle this really ask a lot !!!!)
After a throttling function event is triggered, it cannot be called continuously within a short period of time. The next function call can be made only after the specified period of time has passed after the last function execution. It is generally used for HTTP requests.
If the event is triggered again before the set delay, the last delay operation timer is cleared and the timer is reset.
function conso(){
console.log('is run');
}
var btnUse=true;
$("#btn").click(function() {if(btnUse){
conso();
btnUse=false;
}
setTimeout(function(){
btnUse=true; },1500) // How long after click can execute})Copy the code
2. How to prevent trembling? (Generally asked with throttling, be sure to understand!!)
After the event is triggered multiple times, the event handler is executed only once and at the end of the triggering operation. It is generally used for scroll events.
If the event is triggered again before the set delay, the last delay operation timer is cleared and the timer is reset.
let timer;
window.onscroll = function () {
if(timer){
clearTimeout(timer)
}
timer = setTimeout(function() {// Scroll bar positionlet scrollTop = document.body.scrollTop || document.documentElement.scrollTop;
console.log('Scroll bar position:'+ scrollTop); timer = undefined; }}, 200)Copy the code
Or this:
function debounce(fn, wait) {
var timeout = null;
return function() {
if(timeout ! == null) clearTimeout(timeout); timeout =setTimeout(fn, wait); }} // handle functionsfunction handle() { console.log(Math.random()); } // The scroll event window.adDeventListener ('scroll', debounce(handle, 1000));
Copy the code
2. Guess the result of the following questions?
function Timer() {
this.s1 = 0;
this.s2 = 0;
setInterval(() => this.s1++, 1000);
setInterval(function () {
this.s2++;
}, 1000);
}
var timer = new Timer();
setTimeout(() => console.log('s1: ', timer.s1), 3100);
setTimeout(() => console.log('s2: ', timer.s2), 3100);
Copy the code
The answer is:
s1: 3
s2: 0
Copy the code