In this section, the author collected some JavaScript related knowledge and notes about some related interview questions on Github and other major forums. I will share this summary with you. Thanks to CavsZhouyou for your work. The link to the original article is at the bottom of the article. If there are any errors, please kindly point them out!

  • Attached note link, read the past more quality articles can be moved to view, like can give me a thumbs up to encourage oh: github.com/Wscats/arti…

1. Introduce the basic data types of JS.

There are six basic data types in js: Undefined, Null, Boolean, Number, String. There is also a new Symbol type in ES6, which represents a unique and immutable data type. I think it is mainly to solve the problem of global variable conflicts.Copy the code

2. How many types of values does JavaScript have? Can you draw a memory map of them?

Related knowledge:

  • Stack: raw data type (Undefined, Null, Boolean, Number, String)
  • Heap: Reference data types (objects, arrays, and functions)
The difference between the two types is that the storage location is different. The original data type is a simple data segment directly stored in the stack. It occupies a small space and has a fixed size. It is frequently used data, so it is stored in the stack. Reference data type stored in the heap object, large space, size is not fixed. If stored on the stack, the performance of the program will be affected. The reference data type stores a pointer on the stack to the starting address of the entity in the heap. When the interpreter looks for a reference value, it first retrieves its address in the stack and then retrieves the actual value from the heap.Copy the code

Answer:

Js can be divided into two types of values, one is basic data type, one is complex data type. The basic data type is.... (reference 1) The complex data type refers to the Object type. All other data types, such as Array, Date, etc., can be understood as subclasses of the Object type. The main difference between the two types is that they are stored in different locations. The value of the basic data type is stored directly on the stack, while the value of the complex data type is stored in the heap, and the heap value is obtained by using the corresponding pointer stored on the stack.Copy the code

For more information, see “How many types of Values does JavaScript have?” How many types of values does JavaScript have? Can you draw a memory diagram of them?

3. What is a heap? What is a stack? What are the differences and connections between them?

The concepts of heap and stack exist in data structures and operating system memory. In the data structure, data in the stack is accessed in the first and last way. The heap is a priority queue, sorted by priority, which can be specified by size. A complete binary tree is an implementation of a heap. In an operating system, memory is divided into a stack area and a heap area. The stack memory is automatically allocated and freed by the compiler to store function parameter values, local variable values, and so on. It operates in a similar way to a stack in a data structure. The heap memory is usually allocated and freed by the programmer. If the programmer does not free it, it may be reclaimed by the garbage collection mechanism at the end of the program.Copy the code

For more information, see “What is a heap? What is a stack? What are the differences and connections between them?”.

4. What is the internal attribute [[Class]]?

// All objects (such as arrays) that return typeof "object" contain an internal attribute [[Class]] (we can think of this as an internal Class, not
// Classes in the traditional object-oriented sense). This property cannot be accessed directly, usually by the Object. The prototype. The toString ().. To look at it. Such as:

Object.prototype.toString.call( [1.2.3]);// "[object Array]"

Object.prototype.toString.call( /regex-literal/i );
// "[object RegExp]"
Copy the code

What are the built-in objects in JS?

Related knowledge:

Global objects (globalObjects, or standard built-in objects"Global Object"Confusion. By global objects, WE mean objects in the global scope. Other objects in the global scope can be created by a user's script or provided by a host program. Classification of standard built-in objects (1These global properties return a simple value that has no properties or methods of its own. For example,Infinity,NaN,undefined,nullLiteral (2) function property, global functions can be called directly, do not need to specify the owning object when the call, after the execution will be directly returned to the caller. For example,eval(),parseFloat(),parseInt() (3) Basic objects. Basic objects are the basis on which other objects are defined or used. Basic objects include generic objects, function objects, and error objects. For example,Object,Function,Boolean,Symbol,Error(such as4) Numeric and date objects used to represent numbers, dates, and objects that perform mathematical calculations. For example,Number,Math,Date5) string, an object used to represent and manipulate strings. For example,String,RegExp6) indexable collection objects that represent collections of data sorted by index values, including arrays and arrays of types, as well as array-like objects. For example,Array7Collection objects that use keys to store data, allowing iterating elements in insertion order. For example,Map,Set,WeakMap,WeakSet8) vector set, the data in the SIMD vector set will be organized into a data sequence. For example, SIMD (9Structured data. These objects are used to represent and manipulate structured buffer data, or to useJSONEncoded data. For example,JSON(such as10) control abstract objects for examplePromiseAnd the Generator (11(Reflection for exampleReflect,Proxy12) internationalization, adding ECMAScript objects to support multilingual processing. For example,Intl,IntlThe Collator etc. (13) WebAssembly (14) Other examplesarguments

Copy the code

Answer:

Built-in objects in JS mainly refer to some global value properties, functions and constructor functions defined by JS that exist in global scope before program execution. In general, we often use global variable valuesNaN,undefined, global functions such asparseInt(),parseFloatThe constructor used to instantiate an object is as followsDate,ObjectAnd other built-in objects that provide mathematical calculations, such asMathObject.Copy the code

Detailed information can refer to: “the standard built-in object classification” “JS all built-in object properties and methods summary”

4. 2. Undefined and declared

For variables that have been declared in scope but have not yet been assigned, yesundefined. In contrast, variables that have not been declared in the scope are undeclared. For references to undeclared variables, the browser will report a reference error, such asReferenceError: B is not defined. However, we can use typ Eof's security mechanisms to avoid errors, because for undeclared (or not defined) variables,typeofReturns the"undefined".Copy the code

7. What is the difference between null and undefined?

First of all, Undefined and Null are both basic datatypes. Each of these basic datatypes has only one value, namelyundefinednull.undefinedIt means undefined,nullIs an empty object. A general variable is returned when it is declared but not yet definedundefined.nullIt is used to assign values to variables that may return objects as initialization.undefinedIs not a reserved word in JS, which means we can useundefinedAs a variable name, this approach is very dangerous, it will affect ourundefinedValue judgment. But there are ways to be safeundefinedValue, for examplevoid 0. When we use it for both typestypeofNull typing returns "object" when judging, which is a historical problem. Returns when we compare two types of values with a double equal signtrueReturns when you use three equals signsfalse.Copy the code

For more information, please refer to “JavaScript in-depth Understanding of undefined and NULL”.

8. How do I get a safe undefined value?

becauseundefinedIs an identifier, so it can be used and assigned as a variable, but this affectsundefinedNormal judgment. expressionvoid___ has no return value, so the return result isundefined.voidDoes not change the result of the expression, only that the expression does not return a value. Traditionally we usevoid 0To obtain aundefined.Copy the code

9. What are some basic specifications for writing JavaScript?

In normal project development, we follow some basic norms such as:1All variable declarations in the scope of a function should refer to the head of the functionvarDeclare that two consecutive ones are not allowedvarDeclaration. If the variable has no value, it should be assigned an initial value of the corresponding type, so that others can know the corresponding type value at a glance when reading the code. (2When a string such as address or time appears in your code, you need to use constants instead. (3) When comparing, try to use'= = ='.'! = = 'Instead of'= ='.'! = '. (4Do not add methods to the prototype of a built-in object, such asArray.Date. (5)switchStatements must containdefaultBranch. (6)forLoops must use braces. (7)ifStatements must use braces.Copy the code

10. JavaScript prototypes, prototype chains? What are the characteristics?

In js, we use constructors to create new objects. Each constructor has a Prototype property value inside it. This property value is an object that contains properties and methods that can be shared by all instances of the constructor. When we create an object using the constructor, the object will contain a pointer to the value of the constructor's prototype property. In ES5, this pointer is called the object's prototype. Normally we shouldn't be able to get this value, but browsers now implement the __proto__ attribute to give us access to this attribute, but it's best not to use this attribute because it's not specified in the specification. ES5 has added an object.getPrototypeof () method that allows us to get the prototype of an image. When we access a property of an object, if the property doesn't exist inside the object, then it will look for that property in its prototype object, and that prototype object will have its own prototype, and so on and so forth, the concept of a chain of prototypes. The end of the prototype chain is usually object.prototype, so that's why new objects can use methods like toString(). Features: JavaScript objects are passed by reference, and we don't have a copy of the prototype for each new object entity we create. When we modify the prototype, the objects associated with it inherit the change.Copy the code

For more information, see prototypes and Prototype Chains for JavaScript Insight.

How does js get the prototype?

  • p.proto
  • p.constructor.prototype
  • Object.getPrototypeOf(p)

12. Representation of different base numbers in JS

  • Those starting with 0X or 0X are in hexadecimal format.

  • Octal notation begins with 0, 0O, and 0O.

  • Those starting with 0B or 0B are in binary format.

13. What is the safe range of integers in js?

A safe integer is an integer in this range that can be converted to binary storage without loss of precision. The maximum integer that can be "safely" rendered is 2^ 54-1, or 9007199254740991, defined in ES6 as number.max_safe_INTEGER. The minimum integer is -9007199254740991, defined in ES6 as number.min_safe_INTEGER. If a calculation results in a value that is outside the JavaScript range, the value is automatically converted to the special Infinity value. If a calculation returns a positive or negative Infinity value, the value will not participate in the next calculation. To determine whether a number isFinite, use the isFinite function.Copy the code

14. What is the result of Typeof NaN?

NaNIt means "not a number".NaNIs a "Sentinel value" (regular value with special purpose) used to indicate error conditions in numeric types, i.e., "mathematical operation did not succeed, and this is the result returned after failure."typeof NaN; // "number"

NaNIs a special value that is not equal to itself and is the only value that is not reflexive. whileNaN! =NaNtrue.Copy the code

15. What is the difference between isNaN and number. isNaN?

functionisNaNAfter receiving a parameter, an attempt is made to convert the parameter to a value. Any value that cannot be converted to a value is returnedtrue, so non-numeric values passed in are also returnedtrue, it will affectNaNThe judgment. functionNumberIsNaN will first determine if the passed parameter is a number, and then continue to determine if it isNaN, this method forNaNIs more accurate.Copy the code

16. How does the Array constructor behave when it takes only one value?

When the Array constructor takes only a number, that parameter is treated as the default length of the Array, rather than as an element of the Array. This creates an empty array with the length property set to the specified value. The constructor Array(..) The new keyword is not required. When you don't wear it, it will be automatically replaced.Copy the code

17. Rules for converting other values to strings?

Specification of the9.8Section defines the abstract operation ToString, which handles non-string ToString casts. (1) Null and Undefined,nullconvert"null".undefinedconvert"undefined", (2)BooleanType,trueconvert"true".falseconvert"false". (3)NumberType, but the very small and very large numbers are in exponential form. (4)SymbolType, but only explicit casts are allowed. Using implicit casts produces an error. (3For normal objects, toString() () is called unless you define your own toString() methodObject.prototype.toString()) to return the value of the internal property [[Class]], such as"[object Object]". If the object has its own toString() method, that method is called and its return value is used when it is stringed.Copy the code

18. Rules for converting other values to numeric values?

Sometimes we need to use non-numeric values as numbers, such as mathematical operations. For this purpose, the ES5 specification defines the abstract operation ToNumber in Section 9.3. (1) Convert the value of Undefined to NaN. (2) The value of type Null is converted to 0. (3) Boolean value, true converts to 1, false converts to 0. (4) String values are converted as if using the Number() function. If they contain non-numeric values, they are converted to NaN. Empty strings are 0. (5) The value of type Symbol cannot be converted to a number. (6) Objects (including arrays) are first converted to the corresponding primitive type value, and if a non-numeric primitive type value is returned, it is then cast to a number following the above rules. To convert a value to a valueOf the corresponding primitive type, the abstract operation ToPrimitive first checks (through the internal operation DefaultValue) to see if the value has a valueOf() method. If it has and returns a value of a primitive type, it is cast using that value. If not, the return value of toString(), if present, is used for casting. If neither valueOf() nor toString() returns a base type value, TypeError is generated.Copy the code

19. Rules for converting other values to Boolean values?

Section 9.2 of the ES5 specification defines the abstract operation ToBoolean, which lists all possible results of a Boolean cast. The following values are false: • undefined • null • false • +0, -0, and NaN • "" False Boolean casts result in false. Logically, everything outside the list of false values should be true.Copy the code

20. What is the result of valueOf and toString for {} and []?

ValueOf = {}; toString = "[object object]"; []; toString = ""Copy the code

21. What is a false value object?

In certain cases, browsers create exotic values on top of regular JavaScript syntax. These are called "false value objects." False objects look just like normal objects (they both have properties, etc.), but the most common example of casting them to a Boolean value results in false is document.all, which is an array-like object that contains all the elements on the page, Provided by the DOM (rather than the JavaScript engine) for use by JavaScript programs.Copy the code

22. What does the ~ operator do?

~ returns 2's complement, and ~ converts the number to a 32-bit integer, so we can use ~ to round. Minus x is roughly the same thing as minus x plus 1.Copy the code

23. What’s the difference between parsing a number in a string and casting a string to a number?

Parsing allows strings (such as parseInt()) to contain non-numeric characters, in left-to-right order, stopping if a non-numeric character is encountered. Conversions (such as Nu mber ()) do not allow non-numeric characters, or they will fail and return NaN.Copy the code

24. +When is an operator used for concatenation of strings?

According to section 11.6.1 of the ES5 specification, + concatenates an operand if it is a string or can be converted to a string by following the steps below. If one of its operands is an object (including an array), the ToPrimitive abstraction operation is called first, which in turn is called [[DefaultValue]], with the number as the context. If it cannot be converted to a string, it is converted to a numeric type for computation. In simple terms, string concatenation is performed if one of the operands of + is a string (or is the result of the preceding steps), and number addition is performed otherwise. So for operators other than addition, as long as one side is a number, then the other side is converted to a number.Copy the code

25. When does an implicit cast of a Boolean occur?

(1) If (...) Statement. (2) A. ; . ; ..) Statement (second). (3) While (...) And do.. while(..) A conditional judgment expression in a loop. (4)? Is a conditional judgment expression in:. (5) logical operators | | (logical or) and && (and logic) than the left operand () as a conditional expression.Copy the code

26. | | and && operator returns a value?

&& and | | first judgment can be carried to the first operand condition, if it is not a Boolean value to ToBoolean casts, and then execute condition judgment. For | |, if the condition judgment result to true will return the value of the first operand, if to false will return the value of the second operand. Am&, on the other hand, returns the second operand if true, and the first if false. && and | | return values of them one of the operands, and unconditioned judgment resultCopy the code

27. Casts of Symbol values?

ES6 allows explicit casts from symbols to strings, whereas implicit casts produce errors. The Symbol value cannot be cast to a number (either explicit or implicit results in an error), but it can be cast to a Boolean value (both explicit and implicit results are true).Copy the code

28. Casting rules for the == operator?

(1) Equality comparison between a string and a number, which is performed after the string is converted to a number. (2) Equal comparisons between other types and Boolean types. After the Boolean value is converted to a number, other rules are applied for the comparison. (3) Null and undefined equal comparison, the result is true. Any other value compared with them returns false. (4) Equality comparison between objects and non-objects. The object first calls ToPrimitive abstract operation, and then compares. (5) If an operation value is NaN, the equality comparison returns false (NaN itself is not NaN). (6) If both operation values are objects, compare whether they refer to the same object. The equality operator returns true if both operands point to the same object, and false otherwise.Copy the code

For more information, see comparing JavaScript Strings.

29. How do I convert a string to a number, such as ‘12.3b’?

(1) Use the Number() method, provided that the included string does not contain illegal characters. ParseInt () parseInt() parseInt() parseInt() parseInt() parseInt() parseInt() parseInt() parseInt() parseInt() ¶ You can also set the cardinality of the number to parse. When the cardinality value is 0, or when this parameter is not set, parseInt() determines the cardinality of the number against string. (3) Use the parseFloat() method, which parses a string argument and returns a floating point number. (4) Implicit conversions using the + operator.Copy the code

ParseInt (); parseFloat(); parseFloat(); parseFloat();

30. How do I add a comma to every three digits of the number to the left of the floating point point, for example, 12000000.11 to “12,000,000.11”?

function format(number) {
  return number && number.replace(/ (? ! (^)? =(\d{3})+\.) /g.",");
}
Copy the code

31. Use regular expressions

// (1) Match the hexadecimal color value
var regex = /#([0-9a-fA-F]{6}|[0-9a-fA-F]{3})/g;

// (2) Match the date, for example, yyyY-MM-dd
var regex = / ^ [0-9] {4} - (0 [1-9] | [0-2] 1) - (0 | [1-9] [12] [0-9] [01]) | 3 $/;

// (3) match qq number
var regex = / ^ (1-9] [0-9] {4, 10} $/ g;

// (4) Mobile phone number regular
var regex = /^1[34578]\d{9}$/g;

// (5) The user name is regular
var regex = / ^ [a zA - Z \ $] [a zA - Z0 - _ \ $9] $/ dec {4};
Copy the code

Detailed information can refer to: “front-end form validation commonly used 15 JS regular expressions” “JS commonly used regular summary”

32. Various ways to generate random numbers?

JS – Methods to generate random number summary (different range, type of random number)

33. How to implement random array sort?

// (1) Use the array sort method to sort the array elements randomly. Compare the number from math.random () to 0.5. If it is greater than, return 1; if it is less than, return -1;

function randomSort(a, b) {
  return Math.random() > 0.5 ? -1 : 1;
}

// Cons: The location where each element is sent to the new array is not random, because the sort() method compares in sequence.

// (2) select one element from the original array and add it to the new array

function randomSort(arr) {
  var result = [];

  while (arr.length > 0) {
    var randomIndex = Math.floor(Math.random() * arr.length);
    result.push(arr[randomIndex]);
    arr.splice(randomIndex, 1);
  }

  return result;
}

// (3) swap the elements of the array randomly.

function randomSort(arr) {
  var index,
    randomIndex,
    temp,
    len = arr.length;

  for (index = 0; index < len; index++) {
    randomIndex = Math.floor(Math.random() * (len - index)) + index;

    temp = arr[index];
    arr[index] = arr[randomIndex];
    arr[randomIndex] = temp;
  }

  return arr;
}

// es6
function randomSort(array) {
  let length = array.length;

  if (!Array.isArray(array) || length <= 1) return;

  for (let index = 0; index < length - 1; index++) {
    let randomIndex = Math.floor(Math.random() * (length - index)) + index;

    [array[index], array[randomIndex]] = [array[randomIndex], array[index]];
  }

  return array;
}
Copy the code

More information can be found in Fisher and Yates’ original edition, javascript for Random Array Sorting? JavaScript Learning Notes: Random Array Sorting

34. How many ways can javascript create objects?

We usually use literals to create objects directly, but this creates a lot of duplicate code when creating a large number of similar objects. But unlike ordinary object-oriented languages, JS had no concept of classes before ES6. However, we can use functions to simulate, so as to produce reusable object creation methods. There are several ways I know: (1) The first is the factory pattern. The main working principle of the factory pattern is to use functions to encapsulate the details of creating objects, so as to achieve the purpose of reuse by calling functions. But it has a big problem with creating objects that cannot be associated with a type. It simply encapsulates reusable code without establishing a relationship between the object and the type. (2) The second is the constructor pattern. Every function in js can be a constructor, as long as a function is called by new, then we can call it a constructor. The constructor first creates an object, then points the object's prototype to the constructor's prototype property, then points this in the execution context to the object, and finally executes the entire function. If the return value is not an object, the new object is returned. Since the value of this refers to the newly created object, we can assign a value to the object using this. The advantage of the constructor pattern over the factory pattern is that the object created is linked to the constructor, so we can identify the type of the object through the prototype. But the constructor, a weakness is caused unnecessary function object is created, because in js function is an object, so if the object attribute contains the function, so every time we will create a new function object, wasted unnecessary memory space, because the function is common to all instances. (3) The third mode is the prototype mode, because each function has a Prototype property. This property is an object that contains properties and methods shared by all instances created by the constructor. So we can use prototype objects to add common properties and methods, thereby reusing code. This approach solves the reuse problem of function objects compared to the constructor pattern. However, there are some problems with this pattern. One is that there is no way to initialize values by passing in parameters. The other is that if there is a value of a reference type such as Array, then all instances will share an object, and any change made by one instance to the value of the reference type will affect all instances. (4) The fourth pattern is the combination of the constructor pattern and the prototype pattern, which is the most common way to create custom types. Because both the constructor and prototype patterns are problematic when used separately, we can combine the two patterns, using constructors to initialize object properties and using prototype objects to reuse function methods. This approach does a good job of addressing the disadvantages of using the two patterns alone, but one disadvantage is that it does not encapsulate the code well enough because it uses two different patterns. (5) The fifth mode is the dynamic prototype mode, which moves the creation process of the prototype method assignment to the inside of the constructor. By judging whether the attribute exists, the effect of assigning a value to the prototype object can be realized only once when the function is called for the first time. This approach nicely encapsulates the blend mode above. (6) The sixth pattern is the parasitic constructor pattern, which is implemented in the same way as the factory pattern. My understanding of this pattern is that it is mainly based on an existing type and extends the instantiated object when instantiated. This extends the object without modifying the original constructor. One drawback is that, like the factory pattern, object recognition is not possible. Well, those are the ones I've seen so far.Copy the code

For more information, see “Object Creation with JavaScript in Depth”.

35. How many ways to implement JavaScript inheritance?

I know several ways to implement inheritance in JS: (1) The first way is to implement inheritance in the way of prototype chain, but the disadvantage of this way of implementation is that when the data containing reference type is shared by all instance objects, it is easy to cause confusion of modification. Also, you cannot pass parameters to a supertype when creating a subtype. (2) The second method is to use the borrowed constructor method. This method is implemented by calling the supertype constructor in the subtype function. This method solves the disadvantages of not passing parameters to the supertype, but it has the problem of function method reuse. And the method subtypes defined by the supertype prototype are not accessible. (3) The third approach is composite inheritance, which is a way of combining prototype chains and borrowed constructors. Inheritance of properties of types is achieved by borrowing constructors, and inheritance of methods is achieved by setting archetypes of subtypes to instances of supertypes. This approach solves the problem of using the two patterns separately, but since we prototyped the subtype using an instance of the supertype, we called the constructor of the superclass twice, resulting in a lot of unnecessary attributes in the subtype stereotype. (4) The fourth way is the original type inheritance. The main idea of the original type inheritance is to create a new object based on the existing object. The principle of implementation is to pass an object into the function, and then return an object based on this object as the prototype. The idea of inheritance is not to create a new type, but to achieve a simple inheritance of an Object. The object.create () method defined in ES5 is the implementation of the original type inheritance. The drawbacks are the same as the prototype chain approach. (5) The fifth way is parasitic inheritance. The idea of parasitic inheritance is to create a function that encapsulates the inheritance process by passing in an object, then making a copy of the object, then extending the object, and finally returning the object. This extension process can be understood as inheritance. The advantage of this inheritance is that it is implemented on a simple object, if the object is not of our custom type. The disadvantage is that there is no way to reuse functions. (6) The sixth approach is parasitic composite inheritance, which has the disadvantage of using an instance of a supertype as a prototype for a subtype, resulting in the addition of unnecessary stereotype attributes. Parasitic combination inheritance uses a copy of the stereotype of the supertype as the stereotype of the subtype, thus avoiding the creation of unnecessary attributes.Copy the code

For more information, see inheritance in JavaScript In-depth Understanding.

36. Implementation of parasitic composite inheritance?

function Person(name) {
  this.name = name;
}

Person.prototype.sayName = function() {
  console.log("My name is " + this.name + ".");
};

function Student(name, grade) {
  Person.call(this, name);
  this.grade = grade;
}

Student.prototype = Object.create(Person.prototype);
Student.prototype.constructor = Student;

Student.prototype.sayMyGrade = function() {
  console.log("My grade is " + this.grade + ".");
};
Copy the code

37. Scope chains for Javascript?

The purpose of the scope chain is to ensure orderly access to all variables and functions that the execution environment has access to. Through the scope chain, we can access variables and functions in the outer environment. The scope chain is essentially a list of Pointers to variable objects. A variable object is an object that contains all the variables and functions in the execution environment. The front end of the scope chain is always a variable object for the current execution context. The variable object of the global execution context (that is, the global object) is always the last object in the scope chain. When we look for a variable, we can look backward down the scope chain if it is not found in the current execution environment. The process of creating a scope chain is related to the establishment of an execution context....Copy the code

For more information, see the scope Chain for JavaScript In-depth Understanding.

38. Talk about your understanding of This object.

This is a property in the execution context that points to the object on which the method was last called. In real development, the reference to this can be determined by four invocation modes.Copy the code
  • 1. The first is the function call mode. When a function is not a property of an object and is called directly as a function, this refers to the global object.

  • 2. The second is the method call pattern. If a function is called as a method on an object, this refers to that object.

  • 3. The third is the constructor call pattern. If a function is called with new, a new object is created before the function is executed.

  • 4. The fourth method is the apply, call, and bind mode. These three methods can display the reference to this of the calling function. The apply method takes two arguments: an object bound to this and an array of arguments. The call method receives arguments, the first being the object to which this is bound, and the rest of the arguments that are passed into the function execution. That is, when using the call() method, the arguments passed to the function must be listed one by one. The bind method passes an object and returns a new function that binds this to the passed object. The this point to this function does not change except when new is used.

Of the four, the constructor call pattern has the highest priority, followed by the Apply, call, and bind call pattern, then the method call pattern, and then the function call pattern.Copy the code

This is the best way to understand JavaScript.

39. What does Eval do?

Its function is to parse the corresponding string into JS code and run. You should avoid using eval. It's unsafe and performance intensive (twice, once parsed into a JS statement and once executed).Copy the code

For more information, see eval().

40. What are DOM and BOM?

DOM refers to the Document Object model, which refers to treating a document as an object that defines methods and interfaces for handling web content. BOM refers to the Browser Object model. It refers to treating the browser as an object that defines the methods and interfaces to interact with the browser. The core of the BOM is the window, and the Window object has the dual role of being both an interface to the browser window through JS and a Global object. This means that any object, variable, or function defined in a web page exists as a property or method of the global object. Window objects include locati on objects, Navigator objects, screen objects, and other subobjects. The document object, the most fundamental DOM object, is also a subobject of the BOM window object.Copy the code

For detailed information, please refer to: What’s the difference between DOM, DOCUMENT, BOM and WINDOW? What are DOM and BOM, and how are they related? JavaScript Learning Summary (3) BOM and DOM Details

Write a generic event listener function.

const EventUtils = {
  / / sight, respectively dom0 | | dom2 | | IE way to bind the event
  // Add events
  addEvent: function(element, type, handler) {
    if (element.addEventListener) {
      element.addEventListener(type, handler, false);
    } else if (element.attachEvent) {
      element.attachEvent("on" + type, handler);
    } else {
      element["on"+ type] = handler; }},// Remove events
  removeEvent: function(element, type, handler) {
    if (element.removeEventListener) {
      element.removeEventListener(type, handler, false);
    } else if (element.detachEvent) {
      element.detachEvent("on" + type, handler);
    } else {
      element["on" + type] = null; }},// Get the event target
  getTarget: function(event) {
    return event.target || event.srcElement;
  },

  // Get a reference to the event object, fetching all the information about the event, ensuring that the event can be used at any time
  getEvent: function(event) {
    return event || window.event;
  },

  // Prevent events (mainly event bubble, because IE does not support event capture)
  stopPropagation: function(event) {
    if (event.stopPropagation) {
      event.stopPropagation();
    } else {
      event.cancelBubble = true; }},// Cancel the default behavior of the event
  preventDefault: function(event) {
    if (event.preventDefault) {
      event.preventDefault();
    } else {
      event.returnValue = false; }}};Copy the code

Detailed information can be referred to: “JS Event Model”

42. What is the event? What’s the difference between IE and Firefox’s event mechanism? How do YOU stop bubbling?

  • 1. Events are interactive actions that occur when users operate web pages, such as click/move. In addition to actions triggered by users, events can also be document loading, window scrolling and resizing. The event is encapsulated as an Event object, which contains all the information related to the event (the event properties) and the actions that can be performed on the event (the event methods).

  • 2. Event handling mechanism: IE supports event bubbling and Firefox supports two event models, that is, event bubbling and event capture.

  • 3. Event.stoppropagation () = true;

For more information, please refer to “Javascript Event Model Series (I) events and the Three Models of Events”, “Javascript Event Model: Event Capture and Event Bubble”.

43. What are the three event models?

An event is an interactive action that occurs when a user operates a web page or some operations of the web page itself. Modern browsers have three kinds of event models. The first event model is the original DOM0-level model, which does not propagate, so there is no concept of event flow, but some browsers now support the bubbly implementation, which can define the listener function directly in the web page, or specify the listener function through js properties. This approach is compatible with all browsers. The second event model is IE event model. In this event model, an event has two processes: event processing phase and event bubbling phase. The event processing phase first executes the listener event bound to the target element. Then there is the event bubbling phase, which refers to the event bubbling from the target element to the Document, checking whether the passing node is bound to the event listener function, and executing if so. This model adds listening functions through attachEvent, and you can add multiple listening functions that are executed in sequence. The third is the DOM2-level event model, in which an event has three processes, the first of which is the event capture phase. Capture refers to the event propagating from the Document all the way down to the target element, checking in turn whether the passing node is bound to the event listener function, and executing if so. The latter two phases are the same as the two phases of the IE event model. In this event model, the function bound to the event is addEventListener, where the third parameter specifies whether the event is executed during the capture phase.Copy the code

For more information, see “Bubble or Capture when multiple events are bound to a DOM element.”

44. What is event delegation?

Event delegation essentially takes advantage of the browser event bubbling mechanism. Since events are uploaded to the parent node during the bubbling process, and the parent node can obtain the target node through the event object, the listening function of the child node can be defined on the parent node, and the listening function of the parent node can handle the events of multiple child elements uniformly, which is called event proxy. Using an event agent we can reduce memory consumption by not binding a listener event to each child element. For example, if a new child node is added, we do not need to add a listener event to it. The listener function in the parent element will handle the event.Copy the code

For more information, please refer to the JavaScript Event Delegate Details.

[“1”, “2”, “3”].map(parseInt) what is the answer?

The parseInt() function parses a string and returns an integer. It takes two arguments (val, radix), where radix denotes the radix of the number to be parsed. (The value is between 2 and 36, and the number in the string cannot be larger than the numeric result value.) The map is passed three arguments (element, index, array). By default, the third argument is ignored. Therefore, the three arguments passed are "1-0", "2-1", and "3-2". The first time the base is 0, the decimal parse returns 1.Copy the code

Why [“1”, “2”, “3”].map(parseInt) returns [1,NaN,NaN]?

46. What are closures and why use them?

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 a function that has access to variables local to the current function. Closures have two common uses. The first use of closures is to enable us to access variables inside the function from outside. By using closures, we can access variables inside the function from the outside by calling the closure function from the outside. We can use this method to create private variables. Another use of functions is to keep a variable object in the context of a function that has finished running in memory, because the closure function retains a reference to the variable object, so the variable object is not reclaimed. The nature of closures is a special application of scope chains. Once you know how to create a scope chain, you can understand how closures are implemented.Copy the code

For more information, see JavaScript Closure for Deeper Understanding.

47. “use strict” in javascript code; What does that mean? What’s the difference in using it?

Related knowledge:

Use Strict is a (strict) mode added by ECMAscript5 that makes Javascript run under more stringent conditions. The objectives of the strict model are as follows:Copy the code
  • Eliminate some of the Javascript syntax is not reasonable, not rigorous, reduce some weird behavior;
  • Eliminate the code running some unsafe place, ensure the safety of code running;
  • Improve the compiler efficiency and increase the running speed;
  • Laying the groundwork for future versions of Javascript.

The difference between:

  • 1. Do not use the with statement.
  • 2. Disallow the this keyword to point to global objects.
  • 3. The object cannot have properties with the same name.

Answer:

Use strict refers to the strict operation mode, in which some restrictions are added to the use of JS. For example, disabling this to point to global objects, and disabling the with statement. The purpose of establishing strict mode is mainly to eliminate some unsafe ways of using code, and also to eliminate some unreasonable places of JS syntax itself, so as to reduce some weird behavior at runtime. At the same time, strict running mode can also improve the efficiency of compilation, thus improving the speed of the code. I think strict mode represents a more reasonable, safer and more rigorous development direction of JS.Copy the code

For more information, please refer to “Javascript Strict Mode”.

48. How to tell if an object belongs to a class?

The first is to use the instanceof operator to determine whether the constructor's prototype property appears anywhere in the object's prototype chain. The second way to determine this is through an object's constructor property, which points to the object's constructor, but this is not very safe because the constructor property can be overwritten. The third way, if you need to determine is a built-in reference type, you can use the Object. The prototype, the toString () method to print the Object's [[Class]] attribute to determine.Copy the code

Detailed information can be referred to: “JS judge whether an object belongs to a class”

49. Instanceof?

// The instanceof operator is used to determine whether the constructor's prototype property appears anywhere in the object's prototype chain.
/ / implementation:

function myInstanceof(left, right) {
  let proto = Object.getPrototypeOf(left), // Get the prototype of the object
    prototype = right.prototype; // Get the constructor's prototype object

  // Determine whether the constructor's prototype object is on the prototype chain of the object
  while (true) {
    if(! proto)return false;
    if (proto === prototype) return true;

    proto = Object.getPrototypeOf(proto); }}Copy the code

For more information, see Instanceof.

50. What exactly does the new operator do? How?

// (1) Create a new null object
// (2) Set the object's prototype object to the function's prototype object.
// (3) let this point to this object and execute the constructor code (add properties to the new object).
// (4) Determine the return value type of the function. If it is a value type, return the created object. If it is a reference type, an object of that reference type is returned.

/ / implementation:

function objectFactory() {
  let newObject = null.constructor = Array.prototype.shift.call(arguments),
    result = null;

  // Parameter judgment
  if (typeof constructor! = ="function") {
    console.error("type error");
    return;
  }

  // Create an empty object with the constructor's prototype object
  newObject = Object.create(constructor.prototype);

  // Point this to the new object and execute the function
  result = constructor.apply(newObject, arguments);

  // Determine the return object
  let flag =
    result && (typeof result === "object" || typeof result === "function");

  // Judge the return result
  return flag ? result : newObject;
}

// Usage
// objectFactory(constructor, initialization parameter);
Copy the code

For more information, see “What exactly does the New operator do?” JavaScript In-depth New Simulation Implementation

51. In Javascript, there is a function that executes an object lookup, but never looks for the prototype. What is this function?

HasOwnProperty All objects that inherit Object will inherit the hasOwnProperty method. This method can be used to check if an object has certain properties of its own. Unlike the in operator, this method ignores properties inherited from the stereotype chain.Copy the code

Details you can refer to: the Object. The prototype. HasOwnProperty ()”

52. What about JSON?

Related knowledge:

JSON is a data exchange format, text-based, rather than lightweight, for exchanging data. JSON can represent numbers, Booleans, strings, nulls, arrays (ordered sequences of values), and objects composed of these values (or arrays, objects) (mappings of strings and values). JSON uses JavaScript syntax, but the JSON format is just text. Text can be read in any programming language and passed as a data format.Copy the code

Answer:

JSON is a lightweight text-based data exchange format. It can be read in any programming language and passed as a data format. In project development, we use JSON as a way to exchange data back and forth. At the front end, we serialize a data structure in accordance with JSON format to JSON string, and then pass it to the back end. The back end generates the corresponding data structure after parsing the string in JSON format, so as to realize the transmission of data in front and back ends. Since JSON's syntax is js based, it's easy to confuse objects in JSON with objects in JS. However, it's important to note that JSON is not the same thing as objects in JS. Objects in JSON are more strictly formatted. There is no NaN, so most JS objects are not in the same format as JSON objects. In js, there are two functions to realize the conversion of JS data structure and JSON format. One is the json. stringify function, which passes a data structure conforming to JSON format, and converts it to a JSON string. If the incoming data structure does not conform to the JSON format, special processing is performed on the values during serialization to make them conform to the specification. When the front end sends data to the back end, we can call this function to convert the data object into a string in JSON format. Another function, json.parse (), is used to convert a jSON-formatted string to a JS data structure and will throw an error if the string passed is not a standard JSON-formatted string. When we receive a STRING in JSON format from the back end, we can parse it into a JS data structure using this method to access the data.Copy the code

For more information, see: Inside JSON in JavaScript

53. [].forEach.call($$(““),function(a){a.style.outline=”1px solid #”+(~~(Math.random()(1<<24))).toString(16)})

(1) Select all DOM elements on the page. In the browser's console can use $$() method to get the corresponding elements in the page, this is modern browsers provide a command-line API is equivalent to the document. The querySelectorAll method. (2) Loop through the DOM element (3) add an outline to the element. Since the rendered outline is not in the CSS box model, adding an outline to an element does not affect the size of the element or the layout of the page. (4) Generate random color function. Math.random()*(1<<24) is a random number between 0 and 2^ 24-1, because it is a floating point number, but we only need the integer part, we use the inverse operator ~ to get the integer part twice in a row, and then we use toString(16). Convert to a hexadecimal string.Copy the code

For more information, see “Learning JavaScript in one Line of Code”.

54. What are the methods of js lazy loading?

Related knowledge:

Js lazy loading, which means that the JavaScript file is loaded after the page has loaded. Js lazy loading helps speed up page loading.Copy the code

There are generally the following ways:

  • The defer attribute
  • Async attributes
  • Dynamic DOM creation
  • Use the setTimeout delay method
  • Let JS load last

Answer:

The loading, parsing and execution of JS will block the page rendering process, so we hope that the JS script can be loaded lazily as much as possible to improve the page rendering speed. The first way is that we usually put the JS script at the bottom of the document, so that the JS script can be loaded and executed as late as possible. The second way is to add the defer property to the JS script, which will synchronize the loading of the script with the parsing of the document, and then execute the script file after the document is parsed, so that the rendering of the page is not blocked. Multiple scripts that set the defer property are executed last in order by specification, but this may not be the case in some browsers. The third way is to add async property to the JS script. This property will enable the script to be loaded asynchronously and will not block the page parsing process. However, the JS script will be executed immediately after the script is loaded, and it will also block if the document is not parsed. Scripts with multiple async properties have unpredictable execution orders and generally do not execute in the order of the code. The fourth way is to create the DOM tag dynamically. We can listen to the loading event of the document, and then create the script tag dynamically to introduce THE JS script after the document is loaded.Copy the code

HTML 5

What is Ajax? How do I create an Ajax?

Related knowledge:

The term AJAX was first formally mentioned in February 2005. It is an acronym for Asynchronous JavaScript and XML, which refers to the process of fetching data from an XML document from a server via Asynchronous communication in JavaScript. Update the corresponding part of the current page instead of refreshing the entire page.

In particular, AJAX consists of the following steps.

  • 1. Create the XMLHttpRequest object, that is, create an asynchronous call object
  • 2. Create a new HTTP request and specify the method, URL, and authentication information of the HTTP request
  • 3. Set the function that responds to the HTTP request status change
  • 4. Send an HTTP request
  • 5. Obtain the data returned by the asynchronous call
  • 6. Use JavaScript and DOM to achieve local refresh

General implementation:

const SERVER_URL = "/server";

let xhr = new XMLHttpRequest();

// Create the Http request
xhr.open("GET", SERVER_URL, true);

// Set the status listener function
xhr.onreadystatechange = function() {
  if (this.readyState ! = =4) return;

  // When the request succeeds
  if (this.status === 200) {
    handle(this.response);
  } else {
    console.error(this.statusText); }};// Set the listener function when the request fails
xhr.onerror = function() {
  console.error(this.statusText);
};

// Set the request header
xhr.responseType = "json";
xhr.setRequestHeader("Accept"."application/json");

// Send an Http request
xhr.send(null);

// Promise package implementation:

function getJSON(url) {
  // Create a Promise object
  let promise = new Promise(function(resolve, reject) {
    let xhr = new XMLHttpRequest();

    // Create a new HTTP request
    xhr.open("GET", url, true);

    // Set the listening function for the state
    xhr.onreadystatechange = function() {
      if (this.readyState ! = =4) return;

      // Change the state of the promise when the request succeeds or fails
      if (this.status === 200) {
        resolve(this.response);
      } else {
        reject(new Error(this.statusText)); }};// Set the error listener function
    xhr.onerror = function() {
      reject(new Error(this.statusText));
    };

    // Set the data type of the response
    xhr.responseType = "json";

    // Set the request header
    xhr.setRequestHeader("Accept"."application/json");

    // Send an HTTP request
    xhr.send(null);
  });

  return promise;
}
Copy the code

Answer:

My understanding of Ajax is that it is a method of asynchronous communication, by sending HTTP traffic directly to the server from a JS script, and then updating the corresponding part of a web page based on the data returned by the server, rather than refreshing the entire page. There are a few steps to creating an Ajax first of all you create an XMLHttpRequest object. An HTTP request is then created on this object using the open method. The parameters required by the open method are the method of the request, the address of the request, whether it is asynchronous, and the authentication information of the user. Before making the request, we can add some information and listening functions to the object. For example, we can add header information to the request through the setRequestHeader method. We can also add a state listener to this object. An XMLHttpRequest object has five states. When its state changes, the onReadyStatechange event is triggered. We can set the listener function to handle the result of the successful request. When the readyState of the object becomes 4, it means that the data returned by the server is received. At this time, we can judge the state of the request. If the state is 2xx or 304, it means that the request is returned to normal. At this point, we can use the data in response to update the page. When the properties and listening functions of the object are set, we finally call the sent method to make a request to the server, passing in parameters as the body of data to be sent.Copy the code

Detailed information can be referred to: “XMLHttpRequest object” “From Ajax to FETCH, AXIos” “Fetch introduction” “Traditional Ajax is dead, FETCH is immortal”

56. What about the browser’s caching mechanism?

The browser's caching mechanism refers to keeping a copy of a received Web resource for a period of time. If a request for the resource is made again within the resource's lifetime, the browser uses the cached copy directly, rather than making a request to the server. Using web cache can effectively improve the speed of page opening and reduce unnecessary consumption of network bandwidth. The caching policies of Web resources are usually specified by the server, and can be divided into two types: strong caching policy and negotiated caching policy. When the strong caching policy is used, if the cache resources are valid, the cache resources are used directly without sending requests to the server. A strong caching policy can be set in two ways: the Expires and cache-control attributes in the HTTP header. The server specifies the expiration time of the resource by adding the Expires property to the response header. Within the expiration time, the resource can be cached and used without having to send a request to the server. This time is an absolute time. It is the server time, so there may be problems such as the client time and server time are not consistent, or the user can change the client time, which may affect the cache hit result. Expires is an http1.0 approach, and because of some of its drawbacks, a new header property introduced in HTTP 1.1 is the cache-control property, which provides more precise Control over how resources are cached. This is a relative amount of time. It calculates the expiration time of the resource based on this amount of time and the time when the resource was first requested. Therefore, in contrast to Expires, This is more effective. Common ones, such as private, are used to specify that resources can only be cached by clients and not by proxy servers. N-o-store is used to specify that the resource cannot be cached. No-cache means that the resource can be cached, but it is invalid immediately, and each time a request is sent to the server. Generally, you only need to set one of these methods to implement a strong caching policy, and cache-control takes precedence over Expires when used together. When a negotiated cache policy is used, a request is sent to the server first, and if the resource has not been modified, a 304 state is returned, allowing the browser to use the local cache copy. If the resource has been modified, the modified resource is returned. The negotiated cache can also be set in two ways, using the Etag and last-Modified properties of the HTTP header. The server indicates when the resource was Last Modified by adding a last-modified property to the response header. When the browser next makes a request, it adds an if-modified-since property to the request header. The value of the property is the last-modified value of the Last time the resource was returned. When the request is sent to the server, the server uses this property to compare the last time the resource was modified to determine whether the resource has been modified. If the resource is not modified, the 304 state is returned and the client uses the local cache. If the resource has been modified, the modified resource is returned. The disadvantage of using this method is that the last-modified annotation is accurate only to the second level. If a file has been Modified multiple times in less than a second, the file will have changed but the last-modified file will not change, resulting in inaccurate cache hits. Because of this possible inaccuracy of last-modified, HTTP provides an alternative, the Etag attribute. When the server returns a resource, it adds an Etag attribute to the header. This attribute is the unique identifier generated for the resource, and the value changes as the resource changes. On the next resource request, the browser will add an if-none-match attribute to the request header, the value of which is the value of the Etag of the resource returned last time. After receiving the request, the service compares this value with the current Etag value of the resource to determine whether the resource has changed and whether the resource needs to be returned. In this way, it's more precise than the last-modified approach. When last-Modified and Etag attributes are present at the same time, Etag takes precedence. When using a negotiated cache, the server needs to consider load balancing, so the last-Modified properties of resources on multiple servers should be consistent because Etag values are different on each server, so it is best not to set the Etag attribute when considering load balancing. Both strong-cache and negotiated cache policies use the local cache copy directly when a cache hit occurs, except that the negotiated cache sends a request to the server once. When they don't hit the cache, they send a request to the server to get the resource. In the actual caching mechanism, the strong cache policy and the negotiated cache policy are used together. The browser first determines whether the strong cache is hit based on the request information, and if it is hit, the browser directly uses the resource. If no, the server sends a request to the server based on the header information and uses the negotiation cache. If the negotiation cache matches the request, the server does not return resources and the browser directly uses the copy of the local resource. If the negotiation cache does not match the request, the browser returns the latest resource to the browser.Copy the code

Detailed information can be referred to: “Talking about browser Caching” “Front-end Optimization: Browser Caching Technology introduction” “Cache-Control in request Header” “Cache-Control field value detailed explanation”

57. Does Ajax solve browser caching problems?

  • 1. Before the ajax request plus anyAjaxObj. SetRequestHeader (” the if-modified-since “, “0”).

  • 2. Before the ajax request plus anyAjaxObj. SetRequestHeader (” cache-control “, “no – Cache”).

  • 3. Add a random number to the end of the URL: “fresh=” + math.random (); .

  • “Nowtime =” + new Date().gettime (); .

  • $.ajaxSetup({cache:false}) $.ajaxSetup({cache:false}) So all of the Ajax on the page will execute this statement but there’s no need to save the cache record.

For more information, please refer to: “Solving browser Caching Problems in Ajax” and “Talking about Browser Caching”.

58. What’s the difference between synchronous and asynchronous?

Related knowledge:

Synchronization can be understood as waiting for a value or message from the system after executing a function or method. At this point, the program is blocked and only executes other commands after receiving the returned value or message. Asynchronous, after the execution of a function or method, there is no need to wait for the return value or message, only need to delegate an asynchronous process to the system, so when the system receives the return value or message, the system will automatically trigger the delegated asynchronous process, thus completing a complete process.Copy the code

Answer:

Synchronization means that when a process is executing a request, if the request takes a while to return, the process will wait until the message returns and then continue to execute. Asynchronism is when a process is executing a request, and if the request takes a while to return, the process will continue executing without blocking the message, and then the system will notify the process to process when the message returns.Copy the code

For more information, see the Difference between Synchronous and Asynchronous.

59. What is the browser same-origin policy?

My understanding of the browser's same-origin policy is that JS scripts in one domain cannot access the contents of another domain without permission. Cognate means that the protocols, domain names, and port numbers of the two domains must be the same. Otherwise, the two domains are different. The same origin policy mainly restricts three aspects. The first is that js scripts in the current domain cannot access cookies, localStorage and indexDB in other domains. The second is that js scripts in the current domain cannot operate on the DOM in other domains. The third is that Ajax cannot send cross-domain requests in the current domain. Main aim of the same-origin policy is to ensure that the user information security, it's just a limit of js script, is not the limitation on the browser, for general img or script script requests will not cross-domain limitation, that is because these operations are not through the response result to possible security problems.Copy the code

60. How to solve cross-domain problems?

Related knowledge:

  • 1. Cross domains through JSONP
  • 2. Document. domain + iframe cross-domain
  • 3.location.hash + iframe
  • 4. Window. name + iframe cross-domain
  • 5. PostMessage across domains
  • 6. Cross-domain Resource Sharing (CORS)
  • 7. Nginx agent cross-domain
  • 8. Nodejs middleware proxy is cross-domain
  • 9. The WebSocket protocol is cross-domain

Answer:

Approaches to cross-domain solutions can be divided according to what we want to achieve. First of all, if we just want to implement cross-domain operation of different subdomains under the primary domain, we can use the document. Domain to solve this problem. (1) Set document.domain as the primary domain name to realize cross-domain operation of the same subdomain name. At this time, cookies under the primary domain name can be accessed by the domain name. If the document contains an iframe with the same primary domain but different subdomains, you can perform operations on the iframe. If you want to communicate between different cross-domain Windows, for example if a page wants to communicate with a different source iframe in the page, you can use location.hash or window.name or postMessage. (2) Using the location.hash method, we can dynamically change the hash value of the iframe window on the home page, and then implement the listening function in the iframe window to achieve such a one-way communication. Since there is no way to access the parent window of a different source in the iframe, we can not directly change the hash value of the parent window to achieve communication. We can add another iframe to the iframe, and the content of the iframe is the same as that of the parent page. So we can use window.parent.parent to change the SRC of the top page to achieve two-way communication. (3) The method of window.name is mainly based on the fact that pages of different sources can also be accessed after window.name is set in the same window, so the child pages of different sources can first write data in window.name, and then jump to a page that is the same as the parent. At this point, the page can access the data in the child page of the same origin in window.name. The advantage of this method is that the amount of data can be transferred. (4) Use postMessage, which is a new API in H5. Through it, we can realize the information transfer between multiple Windows. We can get the reference of the specified window, and then call postMessage to send the information. In the window, we can receive the information by listening to the message information, so as to realize the information exchange between different sources. If it is a problem like ajax not being able to submit cross-domain requests, we can use JSONP, CORS, WebSocket protocol, server proxy to solve the problem. (5) Using JSONP to achieve cross-domain requests, its main principle is through the dynamic construction of script tags to achieve cross-domain requests, because the introduction of script tags browser has no cross-domain access restrictions. Through after the requested url to specify a callback function, then the server at the time of return data, build a json data packaging, the packaging is a callback function, and then returned to the front, front end receives the data, because the request is a script file, so will be executed directly, so that we previously defined callback function can be invoked, Thus the processing of cross-domain request is realized. This approach can only be used for GET requests. (6) The use of CORS, CORS is a W3C standard, the full name is "cross-domain resource sharing". CORS requires both browser and server support. Currently, all browsers support this feature, so we only need to configure it on the server side. Browsers divide CORS requests into two categories: simple requests and non-simple requests. For simple requests, the browser issues the CORS request directly. In particular, we add an Origin field to the header. The Origin field is used to describe the source from which the request came. The server uses this value to decide whether to grant the request. If Origin specifies a source that is not within the scope of the license, the server will return a normal HTTP response. The browser notices that the response header does not contain the access-control-allow-Origin field, knows that something went wrong, throws an error, and Ajax does not receive the response. If successful, it will contain some fields beginning with access-control -. For a non-simple request, the browser sends a pre-check request to determine whether the domain name is in the whitelist of the server. The request is made only when the server receives a positive reply. (7) Use the WebSocket protocol, which has no same-origin limitation. (8) Use the server to proxy the cross-domain access request, that is, when there is a cross-domain request operation, send the request to the back end, let the back end to request, and then finally send back the obtained results.Copy the code

Detailed information can be referred to: “Front End Common Cross-domain Solutions (full)”, “Browser Same-origin Policy and how to Circumvent”, “Cross-domain, All you need to know here”, “Why form submissions do not have cross-domain problems, but Ajax submissions have cross-domain problems?”

61. How do I handle cookies when the server proxy forwards?

Detailed information can be referred to: “Nginx”

62. A quick word about cookies?

My understanding is that cookie is a kind of data provided by the server to maintain session state information. It is sent to the browser through the server, and the browser saves it locally. When there is a request of the same origin next time, the saved cookie value is added to the request header and sent to the server. This can be used for functions such as recording user login status. Cookies can generally store 4k of data and can only be shared by web pages of the same origin. The server can use the response header of set-cookie to configure Cookie information. A cookie contains five property values: Expires, Domain, path, Secure, and HttpOnly. Expires specifies the time when a cookie expires, domain is a domain name, and path is a path. Together, domain and path limit which urls a cookie can be accessed. Secure specifies that the cookie can only be transmitted when it is secured. HttpOnly specifies that the cookie can only be accessed by the server, not by js scripts. In the case of XHR cross-domain requests, cookies, even from the same source, are not automatically added to the request header unless indicated.Copy the code

For more information, please refer to: “HTTP Cookies”

63. What about modular development?

My understanding of a module is that a module is a set of methods to implement a particular function. At the beginning, JS only implemented some simple functions, so there was no concept of module, but as the program became more and more complex, the modular development of code became more and more important. Since functions have independent scope, the original writing method is to use functions as modules, several functions as a module, but this way is easy to cause global variable contamination, and the modules have no connection. The object writing approach is presented later, which solves some of the disadvantages of using functions as modules directly by implementing the function as an object method, but this approach exposes all the module members, and external code can modify the values of internal attributes. The most common approach is to write functions that execute immediately, using closures to create the private scope of a module without polluting the global scope.Copy the code

Detailed information can be referred to: “Talking about modular development” “Javascript modular programming (a) : Module writing” “Front-end modular: CommonJS, AMD, CMD, ES6″ Module syntax”

How many module specifications do 64. Js have?

Js is now more mature there are four module loading scheme. The first is the CommonJS solution, which introduces the module through require and defines the module's output interface through module.exports. This module loading scheme is a server-side solution. It introduces modules in a synchronous way, because on the server the files are stored on the local disk, so the reading is very fast, so there is no problem with loading the modules in a synchronous way. On the browser side, however, asynchronous loading is more appropriate because the module is loaded using network requests. The second is the AMD scheme, which uses the mode of asynchronous loading to load the module. The loading of the module does not affect the execution of subsequent statements. All statements that depend on the module are defined in a callback function, and the callback function is executed after the loading is complete. Require.js implements the AMD specification. The third is CMD scheme, this scheme and AMD scheme are to solve the problem of asynchronous module loading, sea. Js implementation of CMD specification. It differs from require.js in that dependencies are handled differently when modules are defined and when dependent modules are executed. The fourth option, proposed by ES6, uses the form of import and export to import and export modules. This scenario is different from any of the three above. Refer to 61.Copy the code

65. What are the differences between AMD and CMD specifications?

The main differences are twofold.

(1) The first aspect is the different handling of dependencies during module definition. AMD is a big fan of dependency prepositioning, where modules are declared when they are defined. CMD, on the other hand, favors proximity, requiring only when a module is needed.

(2) The second aspect is to handle the execution timing of dependent modules differently. First, BOTH AMD and CMD load modules asynchronously. However, the difference between them lies in the execution time of modules. AMD directly executes the dependent modules after they are loaded, and the execution order of the dependent modules may not be consistent with the order we write. CMD, on the other hand, does not execute the dependent modules after they are loaded. It just downloads the modules. After all the dependent modules are loaded, it enters the callback function logic and executes the corresponding modules only when the require statement is encountered, so that the execution order of the modules is consistent with the order in which we write them.

// CMD
define(function(require.exports.module) {
  var a = require("./a");
  a.doSomething();
  // Omit 100 lines here
  var b = require("./b"); Dependencies can be written nearby
  b.doSomething();
  // ...
});

// AMD's default recommendation
define(["./a"."./b"].function(a, b) {
  Dependencies must be written from the start
  a.doSomething();
  // Omit 100 lines here
  b.doSomething();
  // ...
});
Copy the code

Detailed information can be referred to: “Front-end modularity, AMD and CMD differences”

66. Differences between ES6 module and CommonJS module, AMD, CMD.

  • The 1.CommonJS module outputs a copy of the value, and the ES6 module outputs a reference to the value. The CommonJS module outputs a copy of the value, which means that once a value is printed, changes within the module cannot affect it. The ES6 module operates differently from CommonJS. When the JS engine statically analyzes the script, it generates a read-only reference when it encounters the module loading command import. When the script actually executes, the value is then applied to the loaded module based on the read-only reference.

  • The 2.CommonJS module is a runtime load, and the ES6 module is a compile-time output interface. CommonJS modules are objects, that is, when input, the entire module is loaded, an object is generated, and methods are then read from the object. This loading is called “runtime loading.” While an ES6 module is not an object, its external interface is just a static definition, which is generated during the static code parsing phase.

67. What are the core principles of requireJS? (How to load dynamically? How to avoid multiple loading? How is it cached?

The core principle of require.js is to introduce modules asynchronously by dynamically creating script scripts, and then listen for the load event of each script. If each script is loaded, then call the callback function.Copy the code

For more information, see “requireJS: An Analysis of Usage and Principles” and “What are the core principles of requireJS? “Principles of Loading scripts from RequireJs Source Profiling”

How to implement a module loader?

Detailed information can refer to: “JS module loader loading principle is how?”

69. ECMAScript6: How to write class?

In my opinion, the new class added in ES6 is just to add some object-oriented language features that are missing from JS, but it is essentially syntactic sugar, not something new, and the idea of prototype inheritance is behind it. By adding classes, we can organize our code better. Methods that are added to a class are actually added to the prototype of the class.Copy the code

For more information, see ECMAScript 6’s class implementation. What does it mean for JavaScript front-end development? The Basic Grammar of Class

What’s the difference between Documen. write and innerHTML?

The contents of document.write replace the entire document and rewrite the entire page. The contents of innerHTML simply replace the contents of the specified element, overriding only part of the page.Copy the code

For more information on how document.write differs from innerHTML.

71. DOM operations — How do I add, remove, move, replicate, create, and find nodes?

(1) Create a node

createDocumentFragment(node);
createElement(node);
createTextNode(text);
Copy the code

(2) Add, remove, replace, insert

appendChild(node)
removeChild(node)
replaceChild(new,old)
insertBefore(new,old)
Copy the code

(3) Search

getElementById();
getElementsByName();
getElementsByTagName();
getElementsByClassName();
querySelector();
querySelectorAll();
Copy the code

(4) Attribute operations

getAttribute(key);
setAttribute(key, value);
hasAttribute(key);
removeAttribute(key);
Copy the code

Detailed information can be referred to: “DOM overview” “native JavaScript DOM operation summary” “native JS DOM node related API collection”

What’s the difference between innerHTML and outerHTML?

For such an HTML element: <div>content<br/></div>. <br/>; <div>content<br/></div>; InnerText: Internal text, content; OuterText: Internal text, content;Copy the code

73. What’s the difference between call() and.apply()?

They do exactly the same thing; the only difference is the form of the parameters passed in. Apply takes two arguments. The first argument specifies the reference to this object in the function body. The second argument is a collection of objects with lower objects, which can be an array or a class array. Call passes a variable number of arguments. As with apply, the first argument also refers to the "this" point in the function body. After the second argument, each argument is passed to the function in turn.Copy the code

Detailed information can be referred to: “the difference and use of Apply, Call”

74. What is the definition of an array object in JavaScript?

An object that has a length property and several index properties is called an array-like object. An array-like object is like an array, but cannot call the methods of an array. Common array-like objects are the returns of arguments and DOM methods. A function can also be considered an array-like object because it contains the value of the length attribute, which represents the number of arguments that can be accepted.Copy the code

There are several common array-like conversion methods:

(1) The conversion is implemented by calling the slice method of the array

Array.prototype.slice.call(arrayLike);
Copy the code

(2) The conversion is realized by calling the splice method of the array by call

Array.prototype.splice.call(arrayLike, 0);
Copy the code

(3) Use apply to call the concat method of the array to achieve the transformation

Array.prototype.concat.apply([], arrayLike);
Copy the code

(4) Use the array. from method to implement the conversion

Array.from(arrayLike);
Copy the code

Detailed information can be referred to: “JavaScript in-depth such as array objects and arguments” “JavaScript class array” “In-depth understanding of JavaScript class array”

What are the native methods of arrays and objects?

Array and string conversion methods: toString(), toLocalString(), join() where the join() method can specify the delimiter for conversion toString. There are pop() and push() methods that operate on the end of an array. The push method can pass multiple arguments. Reverse () and sort(). Sort () can be passed a function to compare the two values, and if the return value is positive, the positions of the two arguments are swapped. The concatenated array method concat() returns the concatenated array without affecting the original array. The array slice() method is used to slice a part of an array and return it without affecting the original array. The array insert method splice(), which affects how the array finds the index of a particular item, IndexOf() and lastIndexOf() iteration methods every(), some(), filter(), map(), and forEach() array merging methods Reduce () and reduceRight() methodsCopy the code

For more information, see The Detailed Array Types in JavaScript.

76. The fill method for arrays?

The fill() method fills all elements of an array from the start index to the end index with a fixed value. Terminating indexes are not included. The fill method accepts three arguments, value, start, and end. The start and end arguments are optional and default to 0 and the length attribute value of this object, respectively.Copy the code

For more information, see Array.prototype.fill().

77. The length of [,,,]?

The trailing comma (sometimes called the "termination comma") is useful for adding elements, parameters, and attributes to JavaScript code. If you want to add new attributes, and the previous line already uses the trailing comma, you can simply add the new line without modifying the previous line. This makes version control much cleaner and code maintenance less of a hassle. JavaScript originally supported trailing commas in array literals, and later added trailing commas to object literals (ECMAScript 5). More recently (ECMAS cript 2017), it was added to function arguments. However, JSON does not support a comma after the end. If more than one trailing comma is used, there will be a gap. Arrays with gaps are called sparse arrays (dense arrays have no gaps). The length of a sparse array is the number of commas.Copy the code

For more information, please refer to “The Trailing Comma”.

78. Is scope and variable declaration promoted in JavaScript?

The effect of variable promotion is that no matter where we declare a variable in the function, it seems to be promoted to the head of the function, which we can access before the variable is declared without error. The essential reason for the improvement of variable declaration is that the JS engine has a process of parsing before the code execution, creating the execution context and initializing some objects that need to be used when the code is executed. When we visit a variable, we can be carried to the current context to look up the scope chain, and the first end of the scope chain point to is the variable object of the current execution context, the variable object is an attribute of the execution context, which contains the function parameter, all function and variable declarations, the object is created when the code parsing. This is the root cause of variable declaration escalation.Copy the code

For more information, see “Variable Objects in JavaScript in-depth Understanding”.

79. How to write high-performance Javascript?

  • 1. Use bit operations instead of simple four operations.
  • 2. Avoid using deep nested loops.
  • 3. Do not use undefined variables.
  • 4. When you need to access the length of the array multiple times, you can use variables to save, to avoid every time to search for the attribute.

For more information, see how to Write High-performance Javascript?

80. A brief introduction to the V8 garbage collection mechanism

V8's garbage collection mechanism is based on generational collection, which in turn is based on the generation hypothesis, which is characterized by the fact that newly born objects tend to die early and that undead objects live longer. Based on this hypothesis, V8 engines divide memory into old and new generations. Newly created objects or objects that have only been garbage collected once are called the new generation. Objects that have undergone multiple garbage collections are called old generations. The new generation is divided into two Spaces: "From" and "To". Scavenge is applied when the From space is full. The application logic will stop when we run the garbage collection algorithm, and continue when the garbage collection is complete. This algorithm is divided into three steps: (1) First, the surviving objects of the From space are checked. If the objects survive, it is determined whether the objects meet the conditions for promotion to the old generation. If the conditions are met, it is promoted to the old generation. If the condition is not met move To space. (2) If the object does not survive, the space of the object is freed. (3) Finally, the roles of From space and To space are swapped. Be insane. There are two conditions for a Cenozoic object to be promoted to the old generation. (1) The first is to judge whether the object has gone through a Scavenge. If experienced, the object is copied From the From space to the old generation; If no experience, copy To the To space. (2) The second is whether the memory usage of To space exceeds the limit. When an object is copied From the From space To the To space, if the To space usage exceeds 25%, the object is directly promoted To the old generation. The main reason for setting 25% is that after the algorithm ends, the two Spaces will be swapped. If the memory size of the To space is too small, the subsequent memory allocation will be affected. In the old generation, label elimination method and label compression method were adopted. Tag removal first marks the objects that are alive in memory, and then clears those that are not. Since the mark will cause a lot of memory fragmentation, it is not convenient for memory allocation. Therefore, to solve the problem of memory fragmentation, the tag compression method is introduced. Since the logic of the application is paused during the garbage collection, each pause is not very long for the younger generation method because of the small memory, but for the older generation each garbage collection takes a long time, and the pause can have a significant impact. To solve this problem V8 introduced the incremental marking method, which breaks a single pause into multiple steps, alternating one small step at a time with the running logic running for a while.Copy the code

More information can be found in “Understanding how V8 Garbage Collection Works” and “Garbage Collection in JavaScript”.

81. What operations cause memory leaks?

Related knowledge:

  • 1. Unexpected global variables
  • 2. Forgotten timers or callbacks
  • 3. Detach references from the DOM
  • 4. The closure

Answer:

In the first case, we accidentally create a global variable by using an undeclared variable, leaving it in memory unrecyclable. In the second case, we set the setInterval timer and forget to cancel it. If the loop function has a reference to an external variable, the variable will remain in memory and cannot be reclaimed. In the third case, we get a reference to a DOM element, and then the element is deleted, and since we keep the reference to the element, it cannot be retrieved. The fourth is the unreasonable use of closures, which causes some variables to remain in memory.Copy the code

Detailed information can be referred to: “JavaScript memory leak tutorial” “4 types of JavaScript memory leak and how to avoid” “to eliminate the occurrence of four types of MEMORY leak js” “JavaScript typical memory leak and Chrome troubleshooting methods”

82. Requirements: achieve a web site where page operations do not refresh the entire page, and respond correctly when the browser moves forward and backward. Give your technical implementation solution?

By using pushState + Ajax to push the browser forward and back without refreshing, we add a state record to the History object after a successful Ajax call. A state record contains the URL, title, and content properties. The state object is obtained in the popState event, and we can use the content to pass the data. Finally, we respond to the browser's forward and backward actions by listening to the window.onpopState event. There are two problems with pushState, one is that when the home page is opened, there is no record, we can use replaceState to replace the home page record, the other is that when a page is refreshed, it still requests data from the server side. So if the requested URL needs the cooperation of the back end to redirect it to a page.Copy the code

Manipulating the Browser History with pushState and Ajax

83. How do I know if the current script is running in a browser or node environment? (ali)

this === window ? 'browser' : 'node'; If the Global object is not window, the current script is not running in the browser.Copy the code

84. What’s the difference between putting a script tag at the bottom of the page before and after the body closure? How does the browser parse them?

For more information, see “Why put script tag after body tag and before HTML tag?” How to Load Resources from Chrome Source code

85. There is a delay for the click event on the mobile terminal. How long is the delay and why? How to solve this delay?

The reason for the 300ms delay is that the mobile terminal has a double click zoom operation, so the browser has to wait 300ms after the click to see if the user has another click to determine whether the operation is a double click.Copy the code

There are three ways to solve this problem:

  • 1. Disable web page zooming with meta tag.
  • 2. Set the viewport of the page to ideal viewport with the Meta tag.
  • 3. Call some JS libraries such as FastClick
If we register a touchStart event on an element, the event will hide that element. We find that when the element is hidden, it triggers a click event on an element under that element, which is called click penetration.Copy the code

For more information, see: “Mobile 300MS Click Delay and Click Penetration”.

86. What is “front-end routing”? When is it appropriate to use “front-end routing”? What are the advantages and disadvantages of “front-end routing”?

(1) What is front-end routing? Front-end routing is the task of different routes corresponding to different content or pages to the front-end to do, previously through the server returned different pages according to the different URL to achieve. (2) When to use front-end routing? In single-page applications, most of the page structure is unchanged, but only part of the content is changed. (3) What are the advantages and disadvantages of front-end routing? Advantages: good user experience, do not need to capture all from the server, and every time a quick show users faults: single page not remember before the position of the scroll, not in advance, to remember the location of the rolling back Front-end routing a total of two kinds of implementations, one kind is through the way of the hash, one kind is through the use of pushState.Copy the code

Detailed information can refer to: “what is” front-end route “” talk about front-end route” “what is front-end route?”

87. How to test front-end code? BDD, TDD, Unit Test? Know how to test your front-end engineering (Mocha, Sinon, Jasmin, qUnit..) ?

Detailed information can be referred to: “Talking about front-end Unit Testing”

88. What are the ways to check the browser version?

There are two ways to detect the browser version: Is a kind of detection window. The navigator. UserAgent value, but this way is not reliable, because the userAgent can be changed, and early browsers such as ie, It will avoid detection by disguising its userAgent value as Mozilla. The second method is function detection, which is judged according to the unique features of each browser, such as the Unique ActiveXObject under Ie.Copy the code

For more information, see JavaScript to determine Browser Types.

89. What’s a Polyfill?

A Polyfill is code that implements a native API that is not supported by a browser. For example, querySelectorAll is a native Web API that many modern browsers support, but some older browsers don't, so if someone wrote a piece of code that implements this functionality and those browsers also support it, then this would be a Polyfill. A SHIM is a library that has its own API, rather than simply implementing an API that is not supported natively.Copy the code

For more information: Slang in Web Development, what is a Polyfill?

90. Using JS to get file extensions?

// The string.lastIndexof () method returns the last occurrence of the specified value ('.' in this case) in the String in which the method was called, or -1 if not found.

// For 'filename' and '.hiddenFile ', the return value of lastIndexOf is 0 and -1, respectively. The unsigned right-shift operator (>>>) converts -1 to 4294967295 and -2 to 4294967294. This method ensures that the file name is not changed in the edge case.

// String.prototype.slice() extracts the file extension from the index calculated above. If the index is larger than the length of the file name, the result is "".
function getFileExtension(filename) {
  return filename.slice(((filename.lastIndexOf(".") - 1) > > >0) + 2);
}
Copy the code

For more information, please refer to “How to Obtain file Extensions more effectively”.

91. Introduce the throttling and damping of JS?

Related knowledge:

If the event is fired within n seconds, the timer will be reset.

// Function throttling: specifies a unit time, within this unit time, the callback function firing the event can only be executed once, if the same unit time of the event firing multiple times, only one of the effective.

// The implementation of function stabilization
function debounce(fn, wait) {
  var timer = null;

  return function() {
    var context = this,
      args = arguments;

    // If there is a timer, cancel the previous timer and start again
    if (timer) {
      clearTimeout(timer);
      timer = null;
    }

    // Set the timer so that the event interval specified after the event execution
    timer = setTimeout(() = > {
      fn.apply(context, args);
    }, wait);
  };
}

// Implementation of function throttling;
function throttle(fn, delay) {
  var preTime = Date.now();

  return function() {
    var context = this,
      args = arguments,
      nowTime = Date.now();

    // If the interval between two times exceeds the specified time, the function is executed.
    if (nowTime - preTime >= delay) {
      preTime = Date.now();
      returnfn.apply(context, args); }}; }Copy the code

Answer:

Function anti-shaking means that the callback is executed n seconds after the event is fired, and if the event is fired again within n seconds, the time is re-timed. This can be used in some click-request events to avoid sending multiple requests to the back end because of multiple clicks by the user. Function throttling refers to a specified unit of time, in this unit time, the callback function can only be fired once, if the same unit of time in the same event is fired multiple times, only one can take effect. Throttling can be used on the event listener of the Scroll function to reduce the frequency of event calls.Copy the code

Detailed information can be referred to: “easy to understand JS function throttling and function tremble” “JavaScript event throttling and event tremble” “JS tremble and throttling”

92. Object.is() is different from the original comparison operator “===”, “==”?

Related knowledge:

If two equal signs are judged equal, they will be cast during the comparison. Equal signs are equal (strict), and comparisons are made without implicit conversions (false if different types are returned). Is specifically treats NaN, -0, and +0 on the basis of equals, ensuring that -0 and +0 are no longer the same, but object.is (NaN, NaN) will return true. It should not be used as being more lenient or strict than other equivalent comparisons.Copy the code

Answer:

If two equal signs are used to determine the equality, if the two types are inconsistent, the system forcibly converts the two types before comparing them. Return false if the two types are different from each other. When using object. is for equality, it is generally the same as for triequals. It handles some special cases where -0 and +0 are no longer equal and two nans are considered equal.Copy the code

93. The escape, encodeURI, what is the difference between encodeURIComponent?

Related knowledge:

Escape and encodeURI both belong to percent-encoding, which converts illegal URI characters to valid ones in a form similar to %*. The fundamental difference is that escape handles characters other than 0xff by directly using unicode followed by a "%u", while Encode URI uses UTF-8 and adds a "%" to each bytecode in UTF-8. For characters up to 0xFF, the encoding is the same (" %XX ", where XX is the hexadecimal Unicode of the character and is also utF-8 of the character), but the range (which characters are encoded and which characters are not encoded) is different.Copy the code

Answer:

EncodeURI escapes the entire URI, converting illegal characters in the URI to valid characters. Therefore, some characters that have special meaning in the URI are not escaped. EncodeURIComponent is an escape of the components of the URI, so some special characters are escaped as well. Escape and encodeURI have the same effect, but they are different for characters other than unicode encoding 0xff. Escape simply prepended %u to the Unicode encoding of the character. The encodeURI first converts the character to UTF-8 and prefixes each byte with %.Copy the code

Details you can refer to: “what is the difference between the escape, encodeURI, encodeURIComponent?”

94. What is the relationship between Unicode and UTF-8?

Unicode is a set of characters that now holds more than a million characters. Each character corresponds to a different Unicode encoding, which specifies only the binary code of the symbol, but not how that binary code is encoded and transmitted in the computer. Utf-8 is a variable length encoding for Unicode. A character can be expressed in 1 to 4 bytes.Copy the code

For more information, please refer to “Character Encoding In Detail” and “Character Encoding Notes: ASCII, Unicode, and UTF-8.”

What is the event loop for 95. js?

Related knowledge:

An event queue is a queue of tasks that are executed in strict chronological order. The tasks at the top of the queue will be executed first and the tasks at the bottom will be executed last. The event queue executes only one task at a time, and then executes the next task after the task completes. The execution stack is a run container similar to the function call stack. When the execution stack is empty, the JS engine checks the event queue. If it is not empty, the event queue pushes the first task into the execution stack to run.Copy the code

Answer:

Because JS is run in a single thread, the code is executed in order by pushing the execution context of different functions onto the execution stack. If an asynchronous event is encountered while executing synchronous code, the JS engine does not wait for its return. Instead, it suspends the event and continues to execute other tasks in the execution stack. After the asynchronous event is executed, the callback corresponding to the asynchronous event is added to another task queue different from the current execution stack to wait for execution. Task queue can be divided into macro task to column and microtask to column, when the current execution stack of the event execution is completed, JS engine will first determine whether there are tasks in the microtask to column can be executed, if there is, the first event of the microtask queue will be pushed to the stack for execution. When all tasks in the column are executed by the microtask, the macro task is judged to be the task in the column. Microtasks include callbacks for promises, process.nextTick in Node, and MutationObserver that listens for Dom changes. Macro tasks include the execution of script scripts, setTimeout, setInterval, setImmediate and other timed events, as well as I/O operations, UI rendering and so on.Copy the code

Details can refer to: “Browser Event Loop mechanism (Event Loop)” “Detailed explanation of JavaScript event Loop (event loop) mechanism” “What is event Loop?” This Time, Understand JavaScript Execution Thoroughly

96. Deep copy implementation in js?

Related information:

// Shallow copy implementation;

function shallowCopy(object) {
  // Copy only objects
  if(! object ||typeofobject ! = ="object") return;

  // Create an array or an object based on the type of the object
  let newObject = Array.isArray(object) ? [] : {};

  // Iterates over the object and determines that the property of the object is copied
  for (let key in object) {
    if(object.hasOwnProperty(key)) { newObject[key] = object[key]; }}return newObject;
}

// Deep copy implementation;

function deepCopy(object) {
  if(! object ||typeofobject ! = ="object") return;

  let newObject = Array.isArray(object) ? [] : {};

  for (let key in object) {
    if (object.hasOwnProperty(key)) {
      newObject[key] =
        typeof object[key] === "object"? deepCopy(object[key]) : object[key]; }}return newObject;
}
Copy the code

Answer:

Shallow copying refers to copying the value of a property from one object to another. If one property has a value of a reference type, then the address of the reference is copied to the object, so that both objects have a reference of the same reference type. Shallow copies can be implemented using the object.assign and expansion operators. A deep copy, in contrast to a shallow copy, creates a new reference type and copies the corresponding value to it when an attribute value is of a reference type, so the object gets a new reference type instead of a reference to the original type. For some objects, deep copy can be implemented using two functions of JSON, but the JSON format is more strict than the JS format, so the conversion will fail if there is a function or Symbol value in the property value.Copy the code

For more information, please refer to: “Deep and shallow Copy of JavaScript Topics” and “The Way to the Front End Interview”.

Write the call, apply, and bind functions

Related information:

// Call function implementation
Function.prototype.myCall = function(context) {
  // Determine the calling object
  if (typeof this! = ="function") {
    console.error("type error");
  }

  // Get the parameter
  let args = [...arguments].slice(1),
    result = null;

  // Check whether the context was passed in. If not, set it to window
  context = context || window;

  // Sets the calling function as a method of an object
  context.fn = this;

  // Call the functionresult = context.fn(... args);// Delete the attribute
  delete context.fn;

  return result;
};

// Implement the apply function

Function.prototype.myApply = function(context) {
  // Determine whether the calling object is a function
  if (typeof this! = ="function") {
    throw new TypeError("Error");
  }

  let result = null;

  // Check whether the context exists, and if not, window
  context = context || window;

  // Sets functions as methods of objects
  context.fn = this;

  // Call the method
  if (arguments[1]) { result = context.fn(... arguments[1]);
  } else {
    result = context.fn();
  }

  // Delete the attribute
  delete context.fn;

  return result;
};

// Implement the bind function
Function.prototype.myBind = function(context) {
  // Determine whether the calling object is a function
  if (typeof this! = ="function") {
    throw new TypeError("Error");
  }

  // Get the parameter
  var args = [...arguments].slice(1),
    fn = this;

  return function Fn() {
    // Pass in different binding values depending on how the call is made
    return fn.apply(
      this instanceof Fn ? this: context, args.concat(... arguments) ); }; };Copy the code

Answer:

Call function implementation steps:

  • 1. Determine whether the calling object is a function. Even if we define it on the prototype of the function, it may be called by means such as call.
  • 2. Check whether the incoming context object exists. If it does not exist, set it to window.
  • 3. Process the passed parameters and intercept all the parameters after the first parameter.
  • 4. Make the function a property of the context object.
  • 5. Use the context object to call this method and save the returned result.
  • 6. Delete the newly added attribute.
  • 7. Return the result.

To implement the apply function:

  • 1. Determine whether the calling object is a function. Even if we define it on the prototype of the function, it may be called by means such as call.
  • 2. Check whether the incoming context object exists. If it does not exist, set it to window.
  • 3. Make the function a property of the context object.
  • 4. Check whether the parameter value is passed in
  • 4. Use the context object to call this method and save the returned result.
  • 5. Delete the newly added attribute
  • 6. Return the result

Bind (bind);

  • 1. Determine whether the calling object is a function. Even if we define it on the prototype of the function, it may be called by means such as call.
  • 2. Save the reference to the current function and get the values of the remaining parameters.
  • 3. Create a function return
  • 4. If you use apply internally to bind a function call, you need to determine if the function is used as a constructor. In this case, you need to pass the current function’s this to the apply call.

Detailed information can be referred to: “handwritten call, apply and bind functions” “JavaScript in-depth call and apply simulation implementation”

98. Implementation of function Currying

Function currying refers to the technique of converting a function with multiple arguments into a series of functions with one argument.

function curry(fn, args) {
  // Get the length of the parameters required by the function
  let length = fn.length;

  args = args || [];

  return function() {
    let subArgs = args.slice(0);

    // Concatenate all existing parameters
    for (let i = 0; i < arguments.length; i++) {
      subArgs.push(arguments[i]);
    }

    // Determine whether the length of the parameter is sufficient for the function
    if (subArgs.length >= length) {
      // If so, execute the function
      return fn.apply(this, subArgs);
    } else {
      // If not, return the corilized function recursively and wait for the arguments to be passed
      return curry.call(this, fn, subArgs); }}; }/ / es6 implementation
function curry(fn, ... args) {
  returnfn.length <= args.length ? fn(... args) : curry.bind(null, fn, ... args); }Copy the code

For more information, see “Function Currying in JavaScript”.

99. Why 0.1 + 0.2! = 0.3? How to solve this problem?

When a computer computes 0.1+0.2, it is actually calculating the binary representation of the two numbers stored in the computer, and 0.1 and 0.2 have an infinite loop of bits when converted to binary representation. Js stores digits in a 64-bit double precision format. There are only 53 significant digits, and any digits beyond this length will be truncated, causing accuracy loss. This is the first place where accuracy is lost. In two to 64 - bit double precision format of the data to calculate, first will be to order processing, in order to exponent alignment, namely after the decimal point position alignment, calculated again, is usually small order to big order alignment, so small order number in the process of alignment, valid number will move to the right, move over effective digit will be intercepted, This is the second area where precision can be lost. When the two data orders are aligned, the result may exceed 53 significant digits after the addition operation, so the excess digits will also be truncated. This is the third place where precision loss may occur. In cases like this, we can solve the problem by converting it to integers and then doing the operation, and then converting it to the corresponding decimal. We can also subtract the result of adding the two numbers from the right-hand side. If the result of the subtracting is less than a minimal Number, then we can assume that the result is equal, which can be used in es6's number.epsilonCopy the code

For more information, see “Why is decimal 0.1 not well represented in binary?” “Decimal floating point into binary” “binary representation of floating point” “JS floating point storage precision loss principle” “mystery of floating point precision” “JavaScript floating point trap and solution” “0.1+0.2!== 0.3? The Strange ~ operator in JavaScript

Introduction to source code, inverse code and complement code

Source code is a fixed point representation of a binary number in a computer, with the highest bit representing the sign bit and the remaining bits representing the numeric bit. The advantage is easy to distinguish, the disadvantage is not directly involved in the operation. The inverse code of the positive number is the same as its original code; The inverse code of a negative number, the sign bit is 1, and the numeric part is reversed according to the original code. For example, [+7] = 00000111, [+7] = 00000111; [-7] Original = 10000111, [-7] inverse = 11111000. The complement of positive numbers is the same as its original code; The complement of a negative number is its inverse plus 1. For example, [+7] original = 00000111, [+7] inverse = 00000111, [+7] complement = 00000111; [-7] Original = 10000111, [-7] inverse = 11111000, [-7] complement = 11111001 The reason why we use complement to represent negative numbers in computers is that it can extend the addition operation to all numerical calculations, so in digital circuits we only need to consider the design of adder. Instead of setting up new digital circuits for subtraction.Copy the code

For more information, please refer to “About 2’s Complement”.

The last

Finally, if the articles and notes can help or inspire you, please do not hesitate to share your likes and collections, your affirmation is the biggest motivation for me to move forward 😁