1. Js data type, Typeof, instanceof

Basic types: String, number, Boolean, NULL, undefined Reference types: Object, function, array

Typeof: checks data types and returns string, Boolean, number, undefined, object, and function instanceof: checks whether the object is an instanceof someone and returns true or false.

var arr = [11.22.33];

console.log(typeof arr); 			//object
console.log(arr instanceof Array);  //true
Copy the code

The difference between null and null: null denotes an empty object, and undefined denotes a variable that has been declared in scope but not assigned a value

console.log(null= =undefined); // true has the same value
console.log(null= = =undefined); // False has different types

console.log(typeof undefined); // undefined
console.log(typeof null); // object
Copy the code

2. The closure

Lexical scope: A lexical scope is the scope of a definition at the lexical stage. In other words, the lexical scope is determined by where you write the variable and block scopes when you write the code.

function fn1() {
  var x = 10;

  function fn2() {  // Note that the fn2 function does not define local variables
  // All local variables inside fn1 are visible to fn2. But not the other way around
  // This is the Javascript language's "chained scope" structure, where child objects look up all the parent's variables one level at a time.
  // All variables of the parent object are visible to the child object, and vice versa.
    console.log(x); 
  }

  fn2(); // The fn2 function executes inside the fn1 function
}

f1(); / / 10
Copy the code

Closure: a function that has access to a variable in the scope of another function

function fn1() {
  var x = 10;

  function fn2() {  // the fn2 function is the closure
    console.log(x);
  }

  // Fn2 can read local variables in fn1, so if we return fn2, we can read internal variables outside of fn1.
  return fn2;
}

var result = fn1();
result(); / / 10
Copy the code

Closure purpose:

  • The ability to access the lexical scope in which a function is defined (preventing it from being recycled)
  • Privatization variable
  • Simulate block-level scopes
  • Create a module

Disadvantages of closures: Function variables can be kept in memory, and too many closures can cause memory leaks

Finally: To quote two thoughts on closures (Ruan Yifeng), if you can understand the results of the following two pieces of code, you should understand how closures work.

// Snippet 1:
var name = "The Window";varobject = {name : "My Object".getNameFunc : function(){return function(){return this.name; }; }}; alert(object.getNameFunc()());// "The Window"
Copy the code
// Code snippet 2:
var name = "The Window";varobject = {name : "My Object".getNameFunc : function(){var that = this;return function(){returnThat. The name; }; }}; alert(object.getNameFunc()());// "My Object"
Copy the code

3. Prototype, prototype chain

Prototype: The __proto__ property inherent in an object that points to the object’s Prototype property.

Prototype chain: When we access a property of an object, if the property does not exist in the object, we will look for the property in its prototype object, which in turn has its own prototype, and so on and so on. This is the concept of prototype chain. So the prototype chain provides a direction for the object member lookup mechanism.

The characteristics ofJavaScript 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.

4. This point

This represents a reference to the current object.

1. In methods, this refers to the object a to which the method belongs. If the method belongs to an object, this refers to the object B. If the method is global, this refers to window. C, in the case of a constructor call, this refers to the object newly created with new.

2. In events, this represents the element that receives the event

3. The apply(), call(), and bind() call modes, all of which can display the this pointer of the specified calling function. Call () takes a list of arguments. Bind () does not execute immediately. Instead, it returns a function with the context this changed.

5. Scope, scope chain, variable promotion

Scope: Determines the access rights of the currently executing code to certain variables. (Global scope, function scope, block level scope).

Scope chain: The process of looking up a variable level by level from the current scope until it finds the global scope.

Variable promotion (pre-parsing) : In the current scope, variables and functions declared with var and function are pre-declared by the browser before the JS code is executed.

6. Inheritance (ES6 extends, composite inheritance)

Extends (ES6) Note: 1. There is no variable promotion for classes in ES6, so you must define a class before you can instantiate an object from it. 2. Use this for all common attributes and methods in a class.

/ / parent class
class Father {
// The constructor inside the class
  constructor(firstName, secondName) {
    this.firstName = firstName;
    this.secondName = secondName;
  }  
// A normal function in the class
  say() {
    console.log("Methods of the parent class"); }}/ / subclass
class Son extends Father {
  The super keyword is used to access and call functions on the object's parent class. You can call either the constructor of the parent class or the normal function of the parent class
  // Note: subclasses must use super in the constructor before this (the parent constructor must be called first, before the subclass constructor is used)
  constructor(x,y) {
    // Call the parent constructor
    super(firstName, secondName);
    
    // Call a normal function (ok, but meaningless)
    //super.say();}}let s = new Son("Zhang"."Mowgli");
console.log(s.firstName);   / / zhang
s.say();					// Method of the parent class
Copy the code

Use call() to refer this from the parent type to the child type. Make subclass’s prototype object = new parent ()

// Parent constructor
function Father(firstName, secondName) {
  this.firstName = firstName;
  this.secondName = secondName;
  this.have = function () {
    console.log("Father has three villas!!");
  };
}

Father.prototype.rank = function () {
  console.log("Highest rank!");
};

// subconstructor
function Son(firstName) {
  Father.call(this."Li");
}

Son.prototype = new Father(); // This step must be written before creating the subclass object

let s = new Son();
s.have();   // Father has three villas!!
s.rank();   // Highest rank!
Copy the code

7. The difference between ordinary functions and arrow functions

  • Arrow functions are anonymous and cannot be used as constructors. New cannot be used
  • 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

8. What built-in objects are there

  • Global variable values: NaN, undefined
  • Global functions: parseInt(), parseFloat()
  • Constructors: Date, Object, etc

9. The JSON and XML

  • JSON is a lightweight text-based data interchange format. It can be read by any programming language and passed as a data format.
  • In the development of the project, we used JSON as a way of exchanging data between the front and back ends.
  • The front end serializes a jSON-formatted data structure into a JSON string via json.stringify () and passes it to the back end
  • Parse () is used to parse jSON-formatted strings to generate the corresponding data structure, so as to realize the data transfer between the front and back ends.

Compared with JSON, XML still has some disadvantages: XML tag redundancy, large data volume, slow transmission speed XML parsing is difficult, JSON parsing difficulty is almost zero

10. ES6 added

  1. Const (constant)/let is used to declare variables, which are non-repeatable and have block-level scope. There is no variable promotion
  2. Destruct assignment of variables (including arrays, objects, strings, numbers and bools, function parameters), residual operators (… rest)
// Array destruct assignment:
let arr = [11.22.33];
let [a, b, c] = arr;
console.log(a); / / 11
console.log(b); / / 22
console.log(c); / / 33

// Object destruct assignment:
let obj = { name: "Tom".age: 18.address: "UK" };
let { name: x, age, address: z } = obj;
console.log(x); // Tom
console.log(age); / / 18
console.log(z); //UK

// Extend operator (...) Use to fetch all traversable properties of the parameter object and copy them to the current object.

// Basic usage
let person = {name: "Amy".age: 15}; 
letsomeone = { ... person }; someone;//{name: "Amy", age: 15}

// Can be used to merge two objects
let age = {age: 15}; 
let name = {name: "Amy"}; 
letperson = {... age, ... name}; person;//{age: 15, name: "Amy"}
Copy the code
  1. Template string
/ / ${... } to render a variable
// 'as a separator

let user = 'Barret';
console.log(`Hi ${user}! `); // Hi Barret!
Copy the code
  1. Arrow function
  2. Set and Map data structures Set objects allow you to store unique values of any type, either primitive values or key-value pairs that object references Map objects. Any value (object or raw value) can be a key or a value
  3. Promise
  4. Async function
  5. class
  6. The Module grammar (import/export)

11. Shallow copy and deep copy

Shallow copy:

Only one layer is copied, and only references (addresses) are copied at the deeper object level, so both copied objects and copied objects share the same address.Copy the code
  1. Object.assign(target,source)
  2. Es6 object extension operator

Deep copy:

No data is shared between the copied object and the original object, everything is its own exclusive copy.Copy the code
1.$.extend() : we can do a deep copy with the $.extend() method. Thankfully, we can implement recursive extend in jQuery by adding a parameterCopy the code
2.useJSONObject to implement deep copy useJSONThe parse and Stringify methods for global objects are also a neat way to implement deep copy.function jsonClone(obj) {
  return JSON.parse(JSON.stringify(obj));  
  The // json.parse () method parses JSON strings to construct JavaScript values or objects described by the strings.
  The // json.stringify () method converts a JavaScript object or value to a JSON string
}
var clone = jsonClone({ a:1 }); 
Copy the code
3.Encapsulate a function by itself using recursionfunction deepClone(obj) {
  if(! obj ||typeofobj ! = ="object") return;
  let newObj = Array.isArray(obj) ? [] : {};
  for (let key in obj) {
    if (obj.hasOwnProperty(key)) {
      newObj[key] =
        typeof obj[key] === "object"? deepClone(obj[key]) : obj[key]; }}return newObj;
} 
Copy the code

12. If you

Definition: a function can execute only once within n seconds after an event is triggered. If an event is triggered again within n seconds, the function execution time is recalculated.

Usage scenario: Search for input in the search box. Verify the input. Check onchange onInput Event window size Resize. Just after the window adjustment is complete, calculate the window size. Prevent repeated rendering.

const debounce = (fn, wait, immediate) = > {
  let timer = null;
  return function (. args) {
    if (timer) clearTimeout(timer);
    if(immediate && ! timer) { fn.call(this, args);
    }
    timer = setTimeout(() = > {
      fn.call(this, args);
    }, wait);
  };
};
const betterFn = debounce(() = > console.log("Fn anti-shake has been executed."), 1000.true);
document.addEventListener("scroll", betterFn); 
Copy the code

13. The throttle

Definition: When an event is continuously triggered, the compartment is guaranteed to trigger an event once.

Usage Scenarios:

  1. Lazy load, scroll load, load more or listen for scroll bar position;
  2. Baidu search box, search association function;
  3. Prevent high-frequency click to submit, prevent form repeated submission;
 function throttle(fn,wait){
  let pre = 0;
  return function(. args){
      let now = Date.now();
      if( now - pre >= wait){
          fn.apply(this,args); pre = now; }}}function handle(){
  console.log(Math.random());
}
window.addEventListener("mousemove",throttle(handle,1000)); 
Copy the code