1 – scope

1.1 Overview of scope

In general, the name used in a piece of program code is not always valid and available, and the scope of the code that defines the name’s availability is the scope of the name. The use of scopes improves the locality of program logic, enhances the reliability of programs, and reduces name conflicts.

There are two types of scope in JavaScript (pre-ES6) :

  • Global scope
  • Local scope (function scope)

1.2 Global scope

The environment in which all code is executed (inside the entire script tag) or a separate JS file.Copy the code

1.3 Local scope

Acting on the code environment within a function is called a local scope. It is also called function scope because it is related to functions.Copy the code

1.4JS has no block-level scope

  • Block scopes are included by {}.

  • In other programming languages (such as Java, c#, etc.), variables created in an if statement or loop can only be used in the same if statement or loop as the following Java code:

    Java has block-level scope:

    if(true) {int num = 123;
      system.out.print(num);  / / 123
    }
    system.out.print(num);    / / an error
    Copy the code

    {} is a scope in which num cannot be used outside the “{}” variable. JavaScript code, on the other hand, does not report errors.

    There is no block-level scope in JS (prior to ES6)

    if(true) {var num = 123;
      console.log(123); / / 123
    }
    console.log(123);   / / 123
    Copy the code

2 – Scope of variable

In JavaScript, variables can be divided into two types, depending on their scope:Copy the code
  • The global variable
  • A local variable

2.1 Global Variables

Variables declared under a global scope are called global variables (variables defined outside the function).Copy the code
  • Global variables can be used anywhere in the code
  • Variables declared by var in global scope are global variables
  • In special cases, variables declared without var in functions are also global variables (not recommended).

2.2 Local variables

Variables declared in a local scope are called local variables (variables defined inside a function)Copy the code
  • Local variables can only be used inside the function
  • The variables declared by var inside a function are local variables
  • Function parameters are actually local variables

2.3 Differences between global variables and local variables

  • Global variables: they can be used anywhere and are only destroyed when the browser is closed, so they take up a lot of memory
  • Local variables: used only inside functions and initialized when the block of code in which they reside is executed; When the code block is finished running, it is destroyed, thus saving more memory

3 – Scope chain

As long as the code is in a scope, the local scope written inside the function, not written inside any function is in the global scope; If there are functions within a function, then another scope can be created within that scope; Using a chain lookup to determine which data can be accessed by an inner function is called a scope chain, according to the mechanism in **[inner functions can access external function variables]**.

Case analysis1:function f1() {
    var num = 123;
    function f2() {
        console.log( num );
    }
    f2();
}
var num = 456;
f1();
Copy the code

Scope chain: Takes the nearest approach to finding the final value of a variablevar a = 1;
function fn1() {
    var a = 2;
    var b = '22';
    fn2();
    function fn2() {
        var a = 3;
        fn3();
        function fn3() {
            var a = 4;
            console.log(a); / / a value?
            console.log(b); / / the value of b?
        }
    }
}
fn1();
Copy the code

4 – Pre-parsing

4.1 Concepts related to pre-parsing

JavaScript code is executed by a JavaScript parser in the browser.

JavaScript parsers run JavaScript code in two steps:

Pre-parsing and code execution.

  • Pre-resolution: In the current scope, the browser will default to declare or define variables with var and function declarations in memory before the JS code is executed. Pre-resolution is also called variable and function promotion.

  • Code execution: Execute JS statements from top to bottom.

    Note: pre-parsing completes the declaration of variables and functions before the code executes.

4.2 Variable preparsing

Variable declarations are promoted to the top of the current scope; variable assignments are not promoted.

console.log(num);  // What is the result?
var num = 10;      / /?
Copy the code

Note: variable promotion only promotes the declaration, not the assignment

4.3 Function pre-analysis

The declaration of a function is promoted to the top of the current scope, but the function is not called.

fn();
function fn() {
    console.log('print');
}
Copy the code

Result: Console prints string — “Print”

Note: the function declaration represents the whole function, so when the function is promoted, the name of the function represents the whole function, but the function is not called!

4.4 Function expression declaration function problem

Function expressions create functions that perform variable promotion

fn();
var  fn = function() {
    console.log('Guess what?');
}
Copy the code

Error: fn is not a function

Fn = undefined; fn = undefined; fn = undefined; Fn is called before fn is assigned to the function body, in which case fn is undefined, so it cannot be called correctly

5 – object

5.1 Concepts about Objects

  • What is an object?

    In JavaScript, an object is an unordered collection of related properties and methods, and everything is an object, such as strings, numbers, arrays, functions, and so on. Objects are made up of properties and methods.Copy the code
    • 2. A characteristic of a thing, represented by an attribute in an object (commonly used noun).

    • 2. The act of something expressed by means in an object (often a verb).

  • Why do we need objects?

    Variables can be used when storing a single value, and arrays can be used when storing multiple values (groups of values). What if you want to keep a person's full information? For example, the way to save the personal information of "Zhang SAN Crazy" in the array is as follows:Copy the code
    Var arr = [' zhang SAN mad ', 'male ', 128,154];Copy the code

    The disadvantage of using arrays in the above example is that the data can only be accessed by index values. Developers need to clearly clear the ranking of all the data in order to accurately retrieve the data, and when there is a large amount of data, it is impossible to remember the index values of all the data.

    In order to better store a group of data, the object came into being: the object set the attribute name for each data, can access data more semantic, data structure is clear, meaning is obvious, convenient for developers to use.

    The group data recorded using the object is:

    var obj = {
        "name":"Zhang SAN Crazy"."sex":"Male"."age":128."height":154
    }
    Copy the code

    Object expression structure in JS is clearer and more powerful.

5.2 Three Methods of Creating an Object

Create objects using literals

The curly braces {} contain properties and methods that express the concrete object (object); {} takes the form of key-value pairsCopy the code
  • Key: Equivalent to attribute name

  • Value: Equivalent to attribute value, can be any type of value (numeric, string, Boolean, function type, etc.)

    The code is as follows:

    var star = {
        name : 'pink'.age : 18.sex : 'male'.sayHi : function(){
            alert('Hello, everyone.'); }};Copy the code

    In the above code, star is the object created.

  • Use of objects

    • Object properties

      • The “keys” in the “key-value pairs” of an object that store specific data are called the properties of the object, that is, the items in the object that store specific data
    • Object methods

      • The “keys” in the “key-value pairs” of an object that store functions are called the methods of the object, that is, the items in the object that store functions
    • Access properties of an object

      • The property inside the object calls: object. The property name, the little dot., is understood as “of.”

      • Another way to call attributes in an object: the object [‘ attribute name ‘]. Note that attributes in square brackets must be quoted

        Example code is as follows:

        console.log(star.name)     // Invoke the name attribute
        console.log(star['name'])  // Invoke the name attribute
        Copy the code
    • Call a method of an object

      • Method calls inside objects: objects. Method name (), which must be followed by parentheses

        Example code is as follows:

        star.sayHi(); // Call the sayHi method with parentheses
        Copy the code
    • Variable, attribute, function, method summary

      Properties are part of an object, while variables are not. Variables are containers that store data individuallyCopy the code
      • Variable: Separate declaration assignment, separate existence

      • Properties: Variables in an object are called properties and do not need to be declared

        Methods are part of an object, and functions are containers that encapsulate operations individually

      • Function: a separate function that can be called by the function name ()

      • Methods: The functions inside an object are called methods. Methods do not need to be declared. Method name ()”

Create an Object using new Object

  • Creating an empty object

    var andy = new Obect();
    Copy the code

    The built-in constructor Object is used to create the Object, at which point the Andy variable already holds the created empty Object

  • Add attributes and methods to empty objects

    • Add properties and methods to an object the way the object manipulates properties and methods

      Example code is as follows:

    andy.name = 'pink';
    andy.age = 18;
    andy.sex = 'male';
    andy.sayHi = function(){
        alert('Hello, everyone.');
    }
    Copy the code

    Note:

    • Object() : uppercase the first letter
    • New Object() : The new keyword is required
    • Format used: object. Attribute = value;

Use constructors to create objects

  • The constructor

    • Constructor: a special function used to initialize an object, that is, to assign initial values to its member variables. It is always used with the new operator. We can extract some common properties and methods from objects and encapsulate them in this function.

    • Constructor encapsulation format:

      functionConstructor name (parameter1The parameter2The parameter3) {
           this. The property name1= parameter1;
           this. The property name2= parameter2;
           this. The property name3= parameter3;
           this. Method name = function body; }Copy the code
    • The format of the constructor call

      Var obj = new constructor name (argument 1, 2, 3)Copy the code

      In the above code, obj is the object that receives the constructor’s creation.

    • Matters needing attention

      1. The constructor convention is to capitalize the first letter.
      2. Properties and methods in functions need to be preceded by this, which represents the properties and methods of the current object.
      3. The constructor does not need a return to return the result.
      4. When we create an object, we must call the constructor with new.
    • other

      A constructor, such as Stars(), abstracts the common part of an object and encapsulates it in a function. It generally refers to a class of objects, such as new Stars(), which refers to a particular object. The process of creating objects by using the new keyword is also called object instantiation

  • The role of the new keyword

    1. Before the constructor code begins execution, create an empty object;
    2. Modify this to point to the created empty object.
    3. The code that executes the function
    4. After the function completes, return this, the created object

    5.3 Traversing an Object

    for… The IN statement is used to loop over the properties of an array or object.

    The syntax is as follows:

    for(variableinObject name) {// Execute the code here
    }
    Copy the code

    Variables in the syntax are custom, and they need to conform to the naming convention. Usually we write this variable as k or key.

    for (var k in obj) {
        console.log(k);      // where k is the attribute name
        console.log(obj[k]); // obj[k] is the attribute value
    }
    Copy the code