Other chapters:
- HTML & CSS
- Javascript Part 1
- Javascript Part 2
- Vue part
- The React part
- Network part
- Part of the performance
JavaScript
1. What are the data types of JS? How are the values stored
JavaScript has eight data types, including seven basic data types: Undefined, Null, Boolean, Number, String, Symbol (new in ES6 for unique values), and BigInt (new in ES10).
One reference data type — Object (which is essentially an unordered set of name-value pairs). Function, Array, Date, etc. JavaScript does not support any mechanism for creating custom types, and all values will ultimately be one of the eight data types mentioned above.
Raw data type: stored directly in the stack. It occupies a small space and has a fixed size. It is frequently used data and therefore stored in the stack.
Reference data types: Stored in both stack and heap, occupying large space and of variable size. 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 entity from the heap.
2, &&, | | and!!!!! What can each operator do
&&
Called logical and, finds the first virtual-valued expression in its operands and returns it, or returns the last truth-valued expression if no virtual-valued expression is found. It uses a short circuit to prevent unnecessary work.||
Called logic or, finds the first truth expression in its operands and returns it. This also uses a short circuit to prevent unnecessary work. It is used to initialize default parameter values in functions prior to supporting ES6 default function parameters.!!!!!
The operator can cast the value on the right to a Boolean, which is an easy way to convert a value to a Boolean.
3. Js data type conversion
There are only three types of conversion in JS:
- Convert to Boolean(call the Boolean() method)
- Convert to a Number(call the Number(), parseInt(), and parseFloat() methods)
- Convert toString(call.tostring () or String() method)
4. The data type of JS (typeof, instanceof, constructor, the Object. The prototype. ToString, call ()
(1) the typeof
Typeof displays the correct type for primitive types except null
console.log(typeof 2); // number
console.log(typeof true); // boolean
console.log(typeof 'str'); // string
console.log(typeof []); // object [] the data typeof the array is interpreted as object in typeof
console.log(typeof function(){}); // function
console.log(typeof {}); // object
console.log(typeof undefined); // undefined
console.log(typeof null); // object Null's data type is interpreted as object by Typeof
Copy the code
For objects, all but functions display object. Therefore, typeof cannot determine exactly what type a variable is. To determine the correct typeof an object, you can use instanceof
(2) instanceof
Instanceof can correctly determine the type of an object because the internal mechanism is to determine if the prototype of the object can be found in the prototype chain.
console.log(2 instanceof Number); // false
console.log(true instanceof Boolean); // false
console.log('str' instanceof String); // false
console.log([] instanceof Array); // true
console.log(function(){} instanceof Function); // true
console.log({} instanceof Object); // true
// console.log(undefined instanceof Undefined);
// console.log(null instanceof Null);
Copy the code
It can be seen that direct literal values judge data types, while Instanceof can accurately judge reference data types (Array, Function, Object), while basic data types cannot be accurately judged by Instanceof.
The instanceof operator tests whether an object has the prototype property of a constructor in its prototype chain. This means determining whether an object is an instance of a data type (such as Array). Focus on determining whether an object is an instance of a data type. Here the literal value, 2, true, ‘STR’ is not an instance, so the value is judged to be false.
(3) the constructor
console.log((2).constructor === Number); // true
console.log((true).constructor === Boolean); // true
console.log(('str').constructor === String); // true
console.log(([]).constructor === Array); // true
console.log((function() {}).constructor === Function); // true
console.log(({}).constructor === Object); // true
Copy the code
There is a pitfall here that if I create an object and change its prototype, constructor becomes unreliable
function Fn(){};
Fn.prototype=new Array(a);var f=new Fn();
console.log(f.constructor===Fn); // false
console.log(f.constructor===Array); // true
Copy the code
(4) the Object. The prototype. ToString. The call Object prototype method toString (), using the call for civet cats in prince, to borrow from the Object’s toString method
var a = Object.prototype.toString;
console.log(a.call(2));
console.log(a.call(true));
console.log(a.call('str'));
console.log(a.call([]));
console.log(a.call(function(){}));
console.log(a.call({}));
console.log(a.call(undefined));
console.log(a.call(null));
Copy the code
5. What built-in objects does JS have?
The built-in object in JS mainly refers to some global value attributes, functions and constructors used to instantiate other objects that exist in the global scope before the program is executed. In general, we often use the global variable value NaN, undefined, global functions such as parseInt(), parseFloat() used to instantiate Object construction functions such as Date, Object, etc., and provide mathematical calculation of the single built-in Object such as Math Object.
Global object (globalObjects) or standard built-in objects"Global Object"Confusion. When I say global objects, I mean objects in the global scope. Other objects in the global scope can be created by the user's script or provided by the 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 (2Global functions can be called directly without specifying the object to which they belong. The result will be returned to the caller directly after execution. For example,eval(),parseFloat(),parseInt() (3Base 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) number and date objects that represent numbers, dates, and objects that perform mathematical calculations. For example,Number,Math,Date
(5) string, an object that represents and manipulates strings. For example,String,RegExp
(6Indexable collection objects that represent collections of data sorted by index value, including arrays and arrays of types, and objects with array like structures. For example,Array
(7Collection objects that use keys when storing data and support iterating over elements in insert order. For example,Map,Set,WeakMap,WeakSet
(8) vector set, SIMD The data in a vector set is 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,Proxy
(12) internationalization, an object added to ECMAScript to support multilingual processing. For example,Intl,IntlThe Collator etc. (13) WebAssembly (14) Others such asarguments
Copy the code
6. The difference between undefined and undeclared?
A variable declared in scope but not yet assigned is undefined. In contrast, variables that have not been declared in scope are undeclared.
ReferenceError: b is not defined However, we can use typeof’s security precautions to avoid errors because Typeof returns “undefined” for undeclared (or not defined) variables.
7. Null vs. undefined
-
First, Undefined and Null are both basic datatypes, and each of these basic datatypes has only one value, namely Undefined and Null.
-
Undefined means undefined, and null means empty (which is not a real object, note below). . Undefined is returned when a variable is declared but not yet defined. Null is used to initialize variables that may return objects.
Null is not an object, although typeof NULL outputs object, but this is a long-standing JS Bug. In the original version of JS, the 32-bit system was used. For the sake of performance, the type information of the variable was stored at a low level. The beginning of 000 represents an object, while null represents all zeros, so it was wrongly judged as object. Although the internal type determination code has changed, the Bug has persisted.
-
Undefined is not a reserved word in JS, which means we can use undefined as a variable name, which is very dangerous and can affect our judgment of undefined. But there are ways to get a safe undefined value, such as void 0.
-
Null typing returns “object” when we use Typeof to judge two types, which is a relic of history. Returns true when we compare two types of values using a double equal sign, false when we compare two types of values with three equal signs.
8. What are the results of valueOf and toString for {} and []?
ValueOf of {} is {}, and toString is"[object Object]"ValueOf of [] is [], and toString is""
Copy the code
9. Javascript scope and scope chain
Scope: A scope is the area where variables are defined. It has a set of rules for accessing variables that govern how the browser engine looks up variables (identifiers) in the current scope and nested scopes.
Scope chain: The purpose of scope chain is to ensure orderly access to all variables and functions that the executing environment has access to. Through scope chain, we can access variables and functions of the outer environment.
A scope chain is essentially a list of Pointers to a variable object. A variable object is an object that contains all variables and functions in the execution environment. The scope chain is always preceded by the variable object of 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 back down the scope chain if it is not found in the current execution environment.
The creation of a scope chain is related to the establishment of the execution context….
10. How many ways can javascript create objects?
We usually create objects in literal form, but this creates a lot of duplicate code when creating lots of similar objects. But js is different from general object-oriented languages in that it had no concept of classes prior to ES6. However, we can use functions to simulate this to produce reusable object creation methods, which I have seen in several ways:
- The first is factory mode. The main working principle of factory mode 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 is that the object created cannot be associated with a type, it simply encapsulates the reusable code, and does not establish the relationship between the object and the type.
- The second is the constructor pattern. Every function in JS can be used as a constructor, as long as a function is called by new, then we can call it a constructor. Executing the constructor first creates an object, then points the prototype of the object to the constructor’s prototype property, then points this in the execution context to the object, and finally executes the entire function, returning the newly created object if the return value is not an object. Since the value of this refers to the newly created object, we can use this to assign a value to the object. The advantage of the constructor pattern over the factory pattern is that the object created is associated with the constructor, so that we can identify the type of the object from the stereotype. 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.
- The third pattern is the prototype pattern, because each function has a Prototype property, which is an object containing properties and methods that can be shared by all instances created through the constructor. Therefore, we can use prototype objects to add common properties and methods for code reuse. Compared with the constructor pattern, this approach solves the reuse problem of function objects. However, there are some problems with this pattern. One is that there is no way to initialize a value by passing in a parameter, and the other is that if there is a value of a reference type such as Array, then all instances share the same object, and a change in the reference type value of one instance affects all instances.
- The fourth pattern is the combination of the constructor pattern and the stereotype pattern, which is the most common way to create custom types. Because both the constructor pattern and the prototype pattern are problematic to use separately, we can combine the two patterns, using constructors to initialize object properties and using prototype objects to reuse function methods. This approach is a good solution to the disadvantages of using the two patterns separately, but it is not good enough to encapsulate the code because the two different patterns are used.
- The fifth pattern is the dynamic prototype pattern, which moves the creation of the assignment of the prototype method inside the constructor. By checking the presence of the property, you can achieve the effect of assigning the prototype object only once on the first call to the function. This approach nicely encapsulates the above blending patterns.
- The sixth pattern is the parasitic constructor pattern, which is implemented in much the same way as the factory pattern. My understanding of this pattern is that it is based on an existing type and extends the instantiated object at instantiation time. This extends the object without modifying the original constructor. It has the same disadvantage as the factory pattern in that it cannot recognize objects.
11. How many ways to implement JavaScript inheritance?
There are several ways I know how to implement inheritance in JS:
-
(1) The first method is to implement inheritance in the way of prototype chain. However, the disadvantage of this method is that when the data of reference type is contained, it will be shared by all the instance objects, which is easy to cause the confusion of modification. Also, you cannot pass parameters to supertypes when creating subtypes.
-
(2) The second method is to use the borrowed constructor method, which is realized by calling the constructor of the supertype in the function of the subtype. This method solves the disadvantage of not passing parameters to the supertype, but it has one problem is that it cannot realize the reuse of function methods. And the method subtypes defined by the supertype stereotype are not accessible.
-
(3) The third method is combinatorial inheritance, which is a way to use a combination of stereotype chains and borrowed constructors. Inheritance of attributes of a type is achieved by borrowing constructors, and inheritance of methods is achieved by setting the stereotype of a subtype to an instance of a supertype. This solves the problem of using the two patterns separately, but since we prototyped the subtype using an instance of the supertype, we called the superclass constructor twice, resulting in many 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 to the function, and then return an object with this object as the prototype. The idea of inheritance is not to create a new type, but to implement a simple inheritance of an Object. The object.create () method defined in ES5 is an implementation of the original type inheritance. The disadvantage is the same as the prototype chain approach.
-
(5) The fifth method is parasitic inheritance. The idea of parasitic inheritance is to create a function to encapsulate 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 process of extension can be understood as inheritance. The advantage of this inheritance is to implement inheritance on a simple object if the object is not of our custom type. The disadvantage is that there is no way to reuse the function.
-
(6) The sixth method is parasitic combinatorial inheritance. The disadvantage of combinatorial inheritance is that instances of supertypes are used as prototypes of subtypes, resulting in the addition of unnecessary prototype attributes. Parasitic composite inheritance uses a copy of the stereotype of the supertype as the stereotype of the subtype, thus avoiding the creation of unnecessary attributes.
12. Implementation of parasitic combinatorial 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
13. Talk about your understanding of this, call, apply and bind
- In the browser, this points to the window object in global scope;
- In functions, this always refers to the object that last called it;
- In the constructor, this refers to the new object that comes out of new;
- This in call, apply, and bind is strongly bound to the specified object;
- The arrow function this is special. The arrow function this is this in the parent scope, not this in the call. Remember that the first four methods are determined at call time, that is, dynamic, whereas the arrow function’s this pointer is static, which is determined at declaration time;
- Apply, call, and bind are built-in apis for js functions. Calling them can specify the execution of this and also pass arguments.
14. JavaScript prototype, prototype chain? What are the characteristics?
In JS we use constructors to create objects. Each constructor has a prototype property value inside it. This property value is an object containing properties and methods that can be shared by all instances of the constructor. When we create an object using the constructor, the object contains a pointer to the constructor’s prototype property. In ES5, this pointer is called the prototype of the object. Normally we should not be able to get this value, but browsers now implement the proto property to give us access to this property, but it is best not to use this property because it is not specified in the specification. New to ES5 is the object.getProtoTypeof () method, which can be used to retrieve the Object’s prototype.
When we access a property of an object, if that 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 prototype chain. 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 each new object entity we create does not have a copy of its own prototype. When we modify the stereotype, the objects associated with it inherit the change.
15. How to get the prototype from JS?
- p.proto
- p.constructor.prototype
- Object.getPrototypeOf(p)
16. What is a closure and why do you use it?
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 local variables of the current function.
Closures have two common uses.
-
The first use of closures is to enable us to access variables inside functions outside of them. By using closures, we can access variables inside the function externally by calling the closure function externally. We can use this method to create private variables.
-
Another use of a function is to keep a variable object in the context of a function that has already run out of memory. Because the closure retains a reference to the variable object, the variable object is not reclaimed.
function a(){ var n = 0; function add(){ n++; console.log(n); } return add; } var a1 = a(); // Note that the function name is just an identifier (a pointer to the function), and () is the executing function; a1(); / / 1 a1(); //2 The second call to n is still in memory Copy the code
In fact, the essence of closure is a special application of scope chain. As long as you understand the creation process of scope chain, you can understand the implementation principle of closure.
17. What is DOM and BOM?
DOM refers to the Document Object Model, which treats a document as an object that defines the methods and interfaces used to process web content.
BOM refers to the Browser object model, which treats the browser as an object that defines the methods and interfaces for interacting with the browser. At the heart of the BOM is the Window, and the Window object has a dual role as both an interface to access the browser window through JS and a Global object. This means that any object, variable, or function defined in the web page exists as a property or method of the global object. The Window object contains sub-objects such as the Locati on object, the Navigator object, and the Screen object, and the document object, the most fundamental object of the DOM, is also a sub-object of the WINDOW object of the BOM.
18. What are the three event models?
Events are the interactive actions or operations of the web page. There are three event models in modern browsers.
- DOM0 level model: This model does not propagate, so there is no concept of event flow, but some browsers now support bubbling. It can define listeners directly in the web page, or it can specify listeners through JS properties. This approach is compatible with all browsers.
- IE event model: In this event model, an event has two processes, the event processing phase and the event bubbling phase. The event processing phase first executes the listening event for the target element binding. Then there is the event bubbling phase, bubbling 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 it if so. This model uses attachEvent to add listeners. Multiple listeners can be added and executed in sequence.
- Dom2-level event model: In this event model, an event has three processes, the first of which is the event capture phase. Capture means that the event is propagated from the document all the way down to the target element, checking in turn to see if the passing node is bound to an event listener and executing it if it is. The latter two phases are the same as the two phases of the IE event model. In this event model, the event-bound function is addEventListener, where the third parameter specifies whether the event is executed during the capture phase.
19. What is event delegation?
Event delegation essentially leverages the browser event bubbling mechanism. Since the event is uploaded to the parent node during the bubbling process, and the parent node can obtain the target node through the event object, the listener function of the child node can be defined on the parent node, and the listener function of the parent node can uniformly handle the events of multiple child elements, which is called event proxy.
Using the event broker we can reduce memory consumption by eliminating the need to bind a listening event to each child element. In addition, we can also achieve dynamic binding of events by using the event broker. For example, when a new child node is added, we do not need to add a listening event to it. The events occurring in it will be handled by the listener function in the parent element.
20. What is event propagation?
When an event occurs on a DOM element, it does not happen exactly on that element. In “when an event occurs on a DOM element, the event does not occur exactly on that element.
There are three stages of event propagation:
- Capture phase – Events start at the window and work down to each element until the target element event or event.target is reached.
- Target phase – The event has reached the target element.
- Bubble phase – Events bubble up from the target element and then up to each element until they reach the Window.
21. What is event capture?
When an event occurs on a DOM element, it does not happen exactly on that element. In the capture phase, the event starts at the window and goes all the way to the element that triggered the event. Window – > document — — — — — — — — > > HTML body — — — – > target element
<! -- HTML structure -->
<div class="grandparent">
<div class="parent">
<div class="child">1</div>
</div>
</div>
Copy the code
/ / JS code
function addEvent(el, event, callback, isCapture = false) {
if(! el || ! event || ! callback ||typeofcallback ! = ='function') return;
if (typeof el === 'string') {
el = document.querySelector(el);
};
el.addEventListener(event, callback, isCapture);
}
addEvent(document.'DOMContentLoaded'.() = > {
const child = document.querySelector('.child');
const parent = document.querySelector('.parent');
const grandparent = document.querySelector('.grandparent');
addEvent(child, 'click'.function (e) {
console.log('child');
});
addEvent(parent, 'click'.function (e) {
console.log('parent');
});
addEvent(grandparent, 'click'.function (e) {
console.log('grandparent');
});
addEvent(document.'click'.function (e) {
console.log('document');
});
addEvent('html'.'click'.function (e) {
console.log('html');
})
addEvent(window.'click'.function (e) {
console.log('window'); })});Copy the code
The addEventListener method has a third optional argument, useCapture, which defaults to false and events occur during the bubble phase or, if true, during the capture phase. If you click on the Child element, it prints Window, Document, HTML, grandparent, andparent on the console, respectively, which is event capture.