1. Js catches exceptions

const run = (val) = > {
  console.log(val)
}
try {
 // Run the code here
 run(params)
} catch (err) {
// Handle the error here
console.log('error1:', err)
}
Copy the code

When executing the code inside a try, params is undefined, so an error message will appear inside the catch:

2. The closure

  • What a closure means: An expression (usually a function) that has many variables and the environment to which they are bound, and thus those variables are part of that expression
  • A closure is a reference to a function variable that is activated when the function returns. A closure is an area of the stack where no resources are freed when a function returns. The simple closure looks like this:
function f1(){
  var n = 100;
  return function f2(){ alert(++n); }}Copy the code

A closure is formed when a function is executed to create an inner function that is either returned as a value or is somehow retained (a property) before being called. In layman's terms, all JS functions are closures.

  • Pros and cons of closures

    Advantages:
    1. You can read variables inside a function
    2. You can keep these local variables in memory to share variable data.

    Disadvantages:

    1. Because closures cause variables in functions to be stored in memory, which can be very memory consuming, you should not abuse closures, which can cause performance problems for web pages and memory leaks in IE. The solution is to remove all unused local variables before exiting the function.
    2. Closures change the values of variables inside the parent function, outside the parent function. So, if you use a parent function as an object, a closure as its Public Method, and internal variables as its private values, be careful not to arbitrarily change the values of the parent function’s internal variables.

3. Prototype objects and prototype chains

  • prototype:
    1. Each function has an attribute called prototype. The prototype property value is an object (a collection of properties, again!). By default, there is only one attribute called constructor pointing to the function itself.
    2. Each function has a prototype. Each object has a PROTO that can be an implicit prototype. Each object has a proto attribute, and the prototype function that points to the function that created the object determines the scope of the free variables inside the function body when it is defined (not called)