Type a,

① Type: Number, String, Boolean, Null, undefined, object, symbol, bigInt

Basic data type: Object. String, Number, Boolean, NULL, undefined Reference type: object. It contains functions and arraysCopy the code

(2) the typeof output

type The results of
Undefined “undefined”
Null “object”
Boolean “boolean”
Number “number”
BigInt “bigint”
String “string”
Symbol “symbol”
function “function”
[] {}, object

③ How to determine the data type

Typeof, toString(), toLocaleString(), methods to check Array types (instanceof operator, object constructor property, array.isarray ())

④ The difference between null and undefined

  • Null has only one value, Null. Non-existent object.

  • Undefined has only one value and is Undefined. No initialization. Undefined is derived from null.

  • Undefined is undefined and null is defined but null.

Var/let/const

< span style = “max-width: 100%; clear: both; min-height: 1pt;

var a = 100;
console.log(a,window.a);    // 100 100

let b = 10;
console.log(b,window.b);    // 10 undefined

const c = 1;
console.log(c,window.c);    // 1 undefined
Copy the code

(2) let and const do not have variable promotion

console.log(a); // undefined ===> undefined = 100; console.log(b); Let b = 10; let b = 10; console.log(c); Const c = 10; c is not defined ===> const c = 10;Copy the code

③ Let and const declarations form block scopes

if(1){ var a = 100; let b = 10; const c = 1; } console.log(a); Console. log(c) : c is not defined ===> The variable C cannot be foundCopy the code

④ Let and const cannot be declared in the same scope. Var does

var a = 100; console.log(a); // 100 var a = 10; console.log(a); // 10 let a = 100; const a = 10; // console error: Identifier 'a' has already been declared ===>Copy the code

⑤ Temporary storage dead zone

var a = 100; if(1){ a = 10; // If a is not defined let a = 1; // If a is not defined let a = 1; // If a is not defined let a = 1; }Copy the code

6 const

// 1. Once you declare that you must assign, you cannot use null placeholders. // Const a = 100; // const a = 100; const list = []; list[0] = 10; The console. The log (list); // [10] const obj = {a:100}; obj.name = 'apple'; obj.a = 10000; The console. The log (obj); // {a:10000,name:'apple'}Copy the code

For of, for in, forEach,map

  • for… Of loop: With an iterator interface, you can use for… The of loop iterates through its members (attribute values). for… The scope for the OF loop includes arrays, Set and Map structures, some array-like objects, Generator objects, and strings. for… The of loop calls the traverser interface, which returns only properties with numeric indexes. For ordinary objects, for… The of structure cannot be used directly because an error is reported. You must deploy the Iterator interface to use it. You can break the loop.
  • for… In loop: Iterates over an object’s own and inherited enumerable properties without directly fetching the property value. You can break the loop.
  • ForEach: the array can only be traversed without interruption, with no return value (or assumed to be undefined).
  • Map: The array can only be traversed without interruption, and the return value is the modified array.

PS: object.keys () : Returns an array of strings containing all the enumerable properties of a given Object.

I wrote some code to test whether forEach would change the array (note that the array items are complex data types). In addition to forEach, apis like Map have the same problem.

A. this B. this C. this D. this

1. This is a Javascript keyword that represents an internal object automatically generated when a function is run and can only be used inside a function. This refers to the object on which the function is called. The direction of his cannot be determined when the function is defined. Only when the function is executed can it be determined who this refers to. In fact, this finally refers to the object that calls it

  • The orientation of this is not determined at authoring time, but at execution time
  • By default, it points to global, or in the case of the browser, to Window
  • The function is implicitly bound if there is a context where it is called
  • New points to a new object
  • The arrow function does not have its own this. Its so-called this captures its context as its own this, so the arrow function is not called by new, and the so-called this is not changed

Change this to call, apply, bind, or var that=this; To change the direction

② Differences and connections

Call () differs from apply() :

  • Similarities: Both call a method on one object and replace the current object with another (same function)

  • Difference:

    (1) Different writing methods for parameters

    The first argument to call() is the object to which this refers, followed by a list of arguments, which can be of any type. When the first argument is null, undefined, the default point is window.

    ③apply() : The first argument is the object to which this points, and the second argument is an array

Call () differs from bind() :

  • Similarity: Both are used to change the direction of this

  • Difference: Call () changes this pointer and executes a function, bind() changes this and returns a function that binds the new this

Five, the closure

When a function is bounded by references to its surrounding state (lexical environment), closures let you access the scope of its outer function within an inner function. In JavaScript, whenever a function is created, the closure is created at the same time the function is created.

function init() { var name = "Mozilla"; // name is a local variable created by init. Function displayName() {// displayName() is an inner function, a closure alert(name); // use a variable declared in the parent function} displayName(); } init();Copy the code
  • Closures are functions that can read variables inside other functions.
  • Keep the values of these variables in memory at all times.
  • Can cause memory leaks (remove all unused local variables before exiting the function,IE)

Arrow functions and ordinary functions

Arrow functions are equivalent to anonymous functions and simplify function definitions. The arrow function has two formats, one consisting of a single expression followed by {… } and return are omitted. Another can contain more than one statement, in which case {… } and return.

Arrow function

let fun = () => {
    console.log('lalalala');
}
Copy the code

Common function

function fun() {
    console.log('lalla');
}
Copy the code
  • Arrow functions are anonymous and cannot be used as constructors. New cannot be used
  • Arrow functions do not bind arguments and use rest arguments instead… To solve
  • The arrow function does not bind this and captures the this value of its context as its own this value
  • When the arrow function calls a function through call() or apply(), it takes only one argument. This is not affected.
  • Arrow functions have no stereotype attributes
  • Arrow functions should not be treated as Generator functions and the yield keyword should not be used

conclusion

  • The arrow function’s this always refers to its context’s this, and no method can change the reference, such as call(), bind(), apply().
  • The this of an ordinary function refers to the object on which it was called

What’s the difference between call and apply? How are call, Aplly, and Bind implemented internally?

1. The origin of call/apply/bind methods

Call, apply, and bind are all inherited from function. prototype and belong to instance methods.

console.log(Function.prototype.hasOwnProperty('call')) //true
console.log(Function.prototype.hasOwnProperty('apply')) //true
console.log(Function.prototype.hasOwnProperty('bind')) //true
Copy the code

In the above code, all three methods return true, indicating that they all inherit from function. prototype. Of course, ordinary objects, functions, and arrays inherit three methods from the function. prototype object, so all three methods can be used on objects, arrays, and functions.

2. Function.prototype.call()

  • fn.call(obj, arg1, arg2, …) , calls a function with a specified this value and arguments supplied separately (a list of arguments).

The call method of a function instance can specify a reference to this within the function (that is, the scope in which the function is executed), and then call the function within the specified scope. The function is executed immediately.

function keith(a, b) { console.log(a + b); } keith.call(null, 1, 2); / / 3Copy the code

The call() method can pass two arguments. The first argument specifies what this points to inside the function (that is, the scope in which the function is executed), and the second argument is the argument passed when the function is called.

The first argument is required and can be null, undefined, or this, but cannot be null. Set to null, undefined, this indicates that Keith is in global scope. The second parameter must be added one by one. In Apply, it must be added as an array.

One application of the call method is the native method of calling an object. It can also be used to convert an array-like object into an array.

3. Function.prototype.apply()

  • Fn. apply(obj, [argsArray]), calls a function with a specified this value and arguments supplied as an array (or array-like object).

The apply method is similar to the call method in that it changes this to the scope in which the function is executed, and then calls the function in the specified scope. This function is also executed immediately. The only difference is that it takes an array as an argument to the function.

The first argument to the apply method is also the object to which this points. If set to null or undefined or this, it is the same as specifying the global object. The second argument is an array whose members, in turn, are passed as arguments to the original function when called. The arguments of the original function must be added individually in the call method, but in the apply method, they must be added as arrays.

function keith(a, b) { console.log(a + b); } keith.call(null, 2, 3); //5 keith.apply(null, [2, 3]); / / 5Copy the code

Application Scenarios:

  • Find the maximum number in an array: there is no Javascript method for finding the maximum number in an array. Use the apply and math.max methods derived from function. prototype to return the maximum number in an array.
  • Change an empty element of an array to undefinedThrough:applyMethod to change an empty element of an Array to undefined using the Array constructor. Empty elements andundefinedThe difference is that the arrayforEachMethod skips empty elements, but does notUndefined and null. Therefore, when iterating through the inner elements, you get different results.
  • Convert an array-like object: makes use of array objectssliceThe array-like object (such asargumentsObject) to a true array. The object to be processed must have a length attribute and the corresponding numeric key.

4. Function.prototype.bind()

The bind method is used to specify the this point inside the function (the scope in which it was executed) and then return a new function. The bind method does not execute a function immediately.

5. Object to which the callback function is bound

If you use this in a callback function, this will point to a DOM object. Since apply (or call) not only binds to the object on which the function was executed, but also executes the function immediately (as bind does not), you have to write the binding statement inside a function.

6. .Call, apply, bind methods

All three methods are similar, but differ in form, in specifying the problem to which this points inside a function. The above examples can be tried in three ways.

  • A: The first argument is to specify the scope of this inside the function, and then call the function according to the scope specified.
  • B: Both can be passed arguments on function calls. The call, bind methods need to be passed in directly, and the apply methods need to be passed in as an array.
  • C: Call, the apply method executes the function immediately after the call, while bind does not execute the function immediately and needs to execute the function again. It’s kind of a closure.
  • D: The call, apply, and bind methods can also be used to fix the orientation of this using that.

The difference between call, apply, and bind is that the call and apply methods are executed immediately after the call. If you are not familiar with the concept of closures, you can read these two articles: javascript– function parameters and closures.

The New() operator

  • Create an empty Object var obj=new Object();
  • Make the empty object’s stereotype property point to the stereotype chain and set the stereotype chain obj.proto=Func.prototype;
  • Var result= func.call (obj);
  • Determine the return type, return the obj if it is a value, or the reference object if it is a reference type.

New ES6 features

  • New block-level scope (let,const)
  • Provides syntactic sugar (class) for defining classes
  • A new base data type (Symbol)
  • New destruct assignment of variables
  • Function parameters allow default values, rest parameters were introduced, and arrow functions were added
  • New APIS for arrays, such as isArray/FROM/of methods; New array instance methods entries(), keys() and values() are added
  • Object and array extension operators have been added
  • New modularity (import/export) in ES6
  • ES6 added Set and Map data structures
  • ES6 natively provides a Proxy constructor to generate a Proxy instance
  • New generators and Iterators in ES6

Why does setTimeout countdown have errors?

SetTimeout () simply inserts the event into the “task queue” and must wait for the current code (execution stack) to finish before the main thread executes its specified callback function. If the current code is taking a long time, it may wait a long time, so there is no guarantee that the callback will execute at setTimeout(). Therefore, the second parameter of setTimeout() indicates the minimum time, not the exact time.

The HTML5 standard states that the second argument to setTimeout() must be at least 4 milliseconds, and if it is less than that, the default is 4 milliseconds. Before that. Older browsers set the minimum time to 10 milliseconds. In addition, DOM changes, especially those involving page re-rendering, are usually performed at 16-millisecond intervals. RequestAnimationFrame () works better than setTimeout();

9. Prototype and prototype chain

(1) prototype:

Javascript objects have a common property called a stereotype, and the property name is Proto. The stereotype property is a reference to another object, which gives us access to all of its properties and methods.

let numArray = [1, 2, -8, 3, -4, 7];
Copy the code

The Array object has a prototype property pointing to array. prototype. The numArray variable inherits all the properties and methods of array. prototype.

That’s why you can call methods like sort() directly, that is

numArray.__proto__ === Array.prototype // true
Copy the code

When a constructor is created, the instance object inherits the constructor’s stereotype properties, which is a very important property of constructors. The constructor is instantiated in Javascript using the new keyword. Conclusion: Each instance object has a private attribute _ proto _ that points to its constructor’s prototype object.

(2) the prototype chain

Each object has a prototype object, with __proto__ (pronounced: Dunder Proto) points to its prototype Object, inherits methods and properties from it, and the prototype Object may own the prototype, layer by layer, eventually pointing to null(Object.prototype.__proto__ points to null). This relationship is called the Prototype chain, through which one object can have properties and methods defined in other objects.

Conclusion: Each instance object has a private property proto that points to its constructor’s prototype object. Prototype objects also have their own proTo, which layers up until an object’s prototype object is null. These layers of prototypes are the prototype chain.

③ Method of creating an object

  • Literal object
let obj = {};
Copy the code
  • Constructor creation: Constructor creation is used to implement inheritance, polymorphism, encapsulation, and other features in Javascript.
function Animal(name) {
	this.name = name;
}
let cat = new Animal('Tom');
Copy the code
  • Class creation: A new feature introduced in ES6, which is a syntactic sugar based on stereotypes and prototype chain implementations.
class Animal {
  constructor(name) {
    this.name = name;
  }
}
let cat = new Animal('Tom');
Copy the code

(4) Four ways to extend the prototype chain

  • Constructor creation
function Animal(name) { this.name = name; } animal. prototype = {run() {console.log(' run '); } } let cat = new Animal('Tom'); cat.__proto__ === Animal.prototype; // true Animal.prototype.__proto__ === Object.prototype; // trueCopy the code

Pros: Supports current and every imaginable browser (IE5.5 works). This approach is very fast, very standards-compliant, and takes full advantage of JIST optimization.

Disadvantages: In order to use this method, the function in this problem must be initialized. In addition, constructor initialization may introduce unwanted methods and attributes to the generated object.

  • Object.createECMAScript 5 introduces a new method:Object.create(). You can call this method to create a new object. The prototype of the new object is the first argument passed when the create method is called:
var a = {a: 1}; 
// a ---> Object.prototype ---> null
var b = Object.create(a);
b.__proto__ === a; // true
Copy the code

Advantages: Supports all current browsers that are not Microsoft versions or IE9 or later. Allows the __proto__ attribute to be set directly once so that the browser can better optimize the object. Create (null) also allows the creation of an Object without a prototype.

Disadvantages: Internet Explorer 8 or later is not supported. This slow object initialization can become a performance black hole when using the second argument, because each object’s descriptor property has its own descriptor. When dealing with hundreds or thousands of object descriptions in object format, this can cause serious performance problems.

  • Object.setPrototypeOf
Object. SetPrototypeOf (obj, prototype) // var a = {n: 1}; var b = { m : 2 }; Object.setPrototypeOf(a, b); a.__proto__ === b; // trueCopy the code

Pros: Supports all modern browsers and Microsoft Internet Explorer 9+. Allows dynamic manipulation of Object prototypes, even forcing the addition of a prototype to an Object created with object.create (null) without a prototype.

Disadvantages: This method does not perform well and should be abandoned; Dynamic prototyping interferes with browser prototyping optimization; Internet Explorer 8 and later versions are not supported.

  • _proto_ : You can also dynamically set the prototype of an object using _proto_.
var a = { n: 1 };
var b = { m : 2 };
a.__proto__ = b;
a.__proto__ === b; // true
Copy the code

Pros: Supports all modern non-Microsoft browsers and IE11 and above. Setting __proto__ to a non-object value silently fails and no errors are thrown.

Cons: Should be discarded entirely because this behavior is not performing at all; Interfering with the browser’s prototyping optimization; Internet Explorer 10 and later versions are not supported.

Js task

  • Macrotask: A task initiated by a host (browser /node). SetTimeout, setInterval, setImmediate, requestAnimationFrame, I/O, UI Rendering
  • Microtask: a task initiated by the JS engine (microtask precedes macro task), process.nextTick, Promise, Object.observe, mutationObserve

When a task is suspended, the JS engine will divide all tasks into these two queues according to their categories. First, the JS engine will take out the first task from the MacroTask queue (also known as task queue), and then take out all tasks in the MicroTask queue to execute them in sequence. The MacroTask task is then fetched, and the cycle continues until both queues are complete.

The relationship between macro and micro tasks