*JavaScript Fundamentals 5 Scope·Pre-Analysis·Object·Traversal Object

1-scope

1.1 Overview of scope

​ Generally speaking, the name used in a piece of program code is not always valid and usable, and the scope of the code that limits the availability of the name is the scope of the name. The use of scope improves the locality of program logic, enhances program reliability, and reduces name conflicts.

There are two scopes in JavaScript (before es6):

  • Global scope
  • Local scope (function scope)

1.2 Global scope

	作用于所有代码执行的环境(整个script标签内部)或独立的js文件。

1.3 Local scope

	作用于函数内的代码环境,就是局部作用域。 
	因为跟函数有关系,所以也称为函数作用域。

1.4 jS has no block-level scope

  • The block scope is covered by {}.

  • In other programming languages ​​(such as java, c#, etc.), variables created in if statements and loop statements can only be used in this if statement and loop statement, such as the following Java code:

    Java has a block-level scope:

    if(true){
          
          
      int num = 123;
      system.out.print(num);  // 123
    }
    system.out.print(num);    // 报错
    

    ​ The above java code will report an error because {} is a scope in the code, and the declared variable num cannot be used outside of "{ }"; and similar JavaScript code will not report an error.

    There is no block-level scope in js (before ES6)

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

2-Scope of variables

在JavaScript中,根据作用域的不同,变量可以分为两种:
  • Global variable
  • Local variable

2.1 Global variables

在全局作用域下声明的变量叫做全局变量(在函数外部定义的变量)。
  • Global variables can be used anywhere in the code
  • Variables declared by var in the global scope are global variables
  • In special cases, variables declared without var in the function are also global variables (not recommended)

2.2 Local variables

在局部作用域下声明的变量叫做局部变量(在函数内部定义的变量)
  • Local variables can only be used inside the function
  • The variable declared by var inside the function is a local variable
  • The formal parameters of the function are actually local variables

2.3 The difference between global variables and local variables

  • Global variables: can be used in any place, and will only be destroyed when the browser is closed, so it takes up more memory
  • Local variables: only used inside the function. When the code block is executed, it will be initialized; when the code block is finished, it will be destroyed, so it saves more memory space

3-scope chain

​ As long as the code is in the same scope, it is written in the local scope inside the function, and it is in the global scope if it is not written inside any function; if there is a function in the function, then another one can be born in this scope Scope; according to this mechanism in **[internal function can access external function variables]**, chain search is used to determine which data can be accessed by internal functions, which is called scope chain.

案例分析1function f1() {
    
    
    var num = 123;
    function f2() {
    
    
        console.log( num );
    }
    f2();
}
var num = 456;
f1();

Insert picture description here

作用域链:采取就近原则的方式来查找变量最终的值
var 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的值 ?
            console.log(b); //b的值 ?
        }
    }
}
fn1();

Insert picture description here

4-pre-analysis

4.1 Related concepts of pre-analysis

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

The JavaScript parser is divided into two steps when running JavaScript code:

​ Pre-parse and code execution.

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

  • Code execution: JS statements are executed from top to bottom.

    Note: Pre-analysis will complete the declaration of variables and functions before the code is executed.

4.2 Variable pre-analysis

​ The declaration of the variable will be promoted to the top of the current scope, and the assignment of the variable will not be promoted.

console.log(num);  // 结果是多少?
var num = 10;      // ?

Result: undefined
Note: Variable promotion only promotes declaration, not assignment

4.3 Function pre-analysis

​ The declaration of the function will be promoted to the top of the current scope, but the function will not be called.

fn();
function fn() {
    
    
    console.log('打印');
}

Result: console print string — "print"

Note: The function declaration represents the function as a whole, so after the function is promoted, the function name represents the entire function, but the function is not called!

4.4 The problem of function expression declaration function

Function expression creates a function and performs variable promotion

fn();
var  fn = function() {
    
    
    console.log('想不到吧');
}

Result: an error prompt "fn is not a function"

Explanation: Before this piece of code is executed, the variable declaration will be promoted. The value of fn after promotion is undefined; and the call of fn is before the value of fn is assigned to the function body, at this time the value of fn is undefined, so it cannot be called correctly

5-Object

5.1 Related concepts of objects

  • What is an object?

    ​ In JavaScript, an object is an unordered collection of related properties and methods. All things are objects, such as strings, numbers, arrays, functions, and so on.
    Objects are composed of properties and methods.

    • Attributes: the characteristics of things, which are represented by attributes in objects (common nouns)

    • Method: the behavior of things, represented by methods in objects (common verbs)

Insert picture description here

  • Why do you need objects?

    ​ When saving a value, you can use a variable, when saving multiple values ​​(a set of values), you can use an array.

      如果要保存一个人的完整信息呢?
    
      例如,将“张三疯”的个人的信息保存在数组中的方式为:
    
    var arr = [‘张三疯’, ‘男', 128,154];
    

    ​ The disadvantage of using an array to save data in the above example is that the data can only be accessed through index values. Developers need to clear the ranking of all data to accurately obtain the data. When the amount of data is huge, it is impossible to remember all The index value of the data.

    ​ In order to better store a set of data, the object came into being: an attribute name is set for each item of data in the object, and the data can be accessed more semantically, the data structure is clear, the meaning is obvious, and it is convenient for developers to use.

    The set of data on the use object record is:

    var obj = {
          
          
        "name":"张三疯",
        "sex":"男",
        "age":128,
        "height":154
    }
    

    The object expression structure in JS is clearer and more powerful.

5.2 Three ways to create objects

Use literals to create objects

	花括号 { } 里面包含了表达这个具体事物(对象)的属性和方法;{ } 里面采取键值对的形式表示 
  • Key: equivalent to the attribute name

  • Value: equivalent to the attribute value, can be any type of value (number type, string type, boolean type, function type, etc.)

    code show as below:

    var star = {
          
          
        name : 'pink',
        age : 18,
        sex : '男',
        sayHi : function(){
          
          
            alert('大家好啊~');
        }
    };
    

    The star in the above code is the created object.

  • Use of objects

    • Object properties

      • Object storing specific data "on the key" in the object property called "key", that is stored in the object entry specific data
    • Object method

      • The "key" in the "key-value pair" that stores the function in the object is called the method of the object, that is, the item that stores the function in the object
    • Access the properties of the object

      • The property call in the object: object. Property name, this small point. It is understood as "of"

      • Another way to call properties in objects: object ['property name'], note that the properties in square brackets must be quoted

        The sample code is as follows:

        console.log(star.name)     // 调用名字属性
        console.log(star['name'])  // 调用名字属性
        
    • Call object method

      • Method call in the object: object. method name (), pay attention to the parentheses after the method name

        The sample code is as follows:

        star.sayHi(); // 调用 sayHi 方法,注意一定要带后面的括号
        
    • Summary of variables, attributes, functions, and methods

      ​ Attributes are part of the object, and variables are not part of the object. Variables are containers for storing data separately

      • Variable: separate declaration and assignment, exist alone

      • Attributes: The variables in the object are called attributes and do not need to be declared

        ​ The method is a part of the object, and the function is a container that individually encapsulates operations

      • Function: exist alone, can be called by the "function name ()"

      • Method: The function in the object is called the method, and the method does not need to be declared, it can be called by using "object.method name()"

Use new Object to create an object

  • Create an empty object

    var andy = new Obect();
    

    Create an object through the built-in constructor Object, at this time the andy variable has saved the created empty object

  • Add properties and methods to empty objects

    • Add properties and methods to the object by operating the properties and methods of the object

      The sample code is as follows:

    andy.name = 'pink';
    andy.age = 18;
    andy.sex = '男';
    andy.sayHi = function(){
          
          
        alert('大家好啊~');
    }
    

    note:

    • Object(): Capitalize the first letter
    • new Object(): requires the new keyword
    • Format used: object.attribute=value;

Use the constructor to create objects

  • Constructor

    • Constructor: It is a special function that is mainly used to initialize an object, that is, to assign initial values ​​to object member variables. It is always used with the new operator. We can extract some public attributes and methods from the object, and then encapsulate them into this function.

    • Encapsulation format of the constructor:

      function 构造函数名(形参1,形参2,形参3) {
              
              
           this.属性名1 = 参数1;
           this.属性名2 = 参数2;
           this.属性名3 = 参数3;
           this.方法名 = 函数体;
      }
      
    • The calling format of the constructor

      var obj = new 构造函数名(实参1,实参2,实参3)
      

      In the above code, obj receives the object created by the constructor.

    • Precautions

      1. The first letter of the constructor is capitalized by convention .
      2. You need to add this before the properties and methods in the function to indicate the properties and methods of the current object.
      3. There is no need to return in the constructor to return the result .
      4. When we create an object, we must use new to call the constructor .
    • other

      The constructor, such as Stars(), abstracts the public part of the object and encapsulates it in a function. It generally refers to a certain class (class) to
      create an object, such as new Stars(), which specifically refers to a certain one. The object is created through the new keyword The process of object instantiation

  • The role of the new keyword

    1. Before the constructor code starts to execute, create an empty object;
    2. Modify the point of this to point this to the created empty object;
    3. Code that executes the function
    4. After the function is completed, return this—that is, the created object

    5.3 Iterating over objects

    The for...in statement is used to loop through the attributes of an array or object.

    ​ Its syntax is as follows:

    for (变量 in 对象名字) {
          
          
        // 在此执行代码
    }
    

    ​ The variable in the grammar is custom, it needs to conform to the naming convention, usually we will write this variable as k or key.

    for (var k in obj) {
          
          
        console.log(k);      // 这里的 k 是属性名
        console.log(obj[k]); // 这里的 obj[k] 是属性值
    }
    

Guess you like

Origin blog.csdn.net/weixin_48116269/article/details/107956410