scope
Scope overview
Generally speaking, the name used in a piece of program code is not always valid and usable, and the code scope that limits the availability of this name is the scope of this name. The use of scope improves the locality of program logic, enhances the reliability of the program, and reduces name conflicts. There are two scopes in JavaScript (before es6):
global scope
copyApplicable to the environment in which all code executes(entire script label inside)or an independent js document.
local scope
copyThe code environment acting on the function is the local scope. Because it is related to functions, it is also called function scope.
JS doesn't have block scope
Block scope is enclosed 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 this loop statement, such as the following Java code:
java has block-level scope:
copyif(true){ int num = 123; system.out.print(num); // 123 } system.out.print(num); // report error
The above java code will report an error because { } in the code is a scope, and the variable num declared in it cannot be used outside of "{ }";
And similar JavaScript code will not report an error:
copyif(true){ var num = 123; console.log(123); //123 } console.log(123); //123
variable scope
In JavaScript, according to different scopes, variables can be divided into two types:
- global variable
- local variable
global variable
copyVariables declared in the global scope are called global variables (variables defined outside the function).
- Global variables can be used anywhere in the code
- Variables declared with var in the global scope are global variables
- As a special case, variables declared without var inside a function are also global variables (not recommended)
local variable
copyVariables declared under the local scope are called local variables (variables defined inside the function)
- Local variables can only be used inside the function
- Variables declared with var inside a function are local variables
- Function parameters are actually local variables
2.3 The difference between global variables and local variables
- Global variables: can be used anywhere, and will only be destroyed when the browser is closed, so it takes up more memory
- Local variable: used only inside the function, it will be initialized when the code block where it is located is executed; it will be destroyed when the code block runs, thus saving more memory space
scope chain
copyAs long as the code is in the same scope, the local scope written inside the function is in the global scope if it is not written inside any function; if there are functions in the function, then another role can be born in this scope domain; according to the**[Inner functions can access outer function variables]**This mechanism, which uses chain lookup to determine which data can be accessed by internal functions, is called scope chain Case study 1:
copyfunction f1() { var num = 123; function f2() { console.log( num ); } f2(); } var num = 456; f1();
copyScope chain: take the approach of the principle of proximity to find the final value of the variable.
copyvar 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); //the value of a? console.log(b); //the value of b? } } } fn1();
pre-parsing
4.1 Related concepts of pre-parsing
copyJavaScript code is generated by the browser in the JavaScript parser to execute. JavaScript parser is running JavaScript Code is divided into two steps: pre-parsing and code execution.
- Pre-parsing: In the current scope, before the JS code is executed, the browser will pre-declare or define variables with var and function declarations in memory by default.
- Code execution: Execute JS statements from top to bottom. Preparsing will complete the declaration of variables and functions before the code is executed.
4.2 Variable pre-parsing
copyPreparsing is also called variable and function promotion. Variable promotion (variable pre-parsing): 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.
copyconsole.log(num); // What was the result? var num = 10; // ?
copyresult: undefined Notice:**Variable promotion only promotes declarations, not assignments**
4.3 Function pre-parsing
copyFunction hoisting: The declaration of the function will be hoisted to the top of the current scope, but the function will not be called.
copyfn(); function fn() { console.log('Print'); }
copyResult: the console prints the string --- "Print" Note: The function declaration represents the whole function, so after the function is promoted, the function name represents the whole function, but the function is not called!
4.4 Function expression declaration function problem
copyThe function expression creates a function, which will perform variable promotion. At this time, the variable name of the receiving function cannot be called correctly:
copyfn(); var fn = function() { console.log('Can't think of it'); }
copyResult: error message " fn is not a function" Explanation: Before the code is executed, the variable declaration will be promoted. fn The value after boosting is undefined;and fn call is in fn Before being assigned to the function body, at this time fn The value is undefined,so it cannot be called correctly
object
related concepts of 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, etc. Objects are made up of properties and methods.
- Attribute: the characteristics of things, represented by attributes in objects (common nouns)
- Method: the behavior of a thing, represented by a method in an object (common verb)
Why do you need objects?
When storing a single value, you can use a variable, and when storing multiple values (a set of values), you can use an array.
What if you want to save a person's complete information?
For example, the way to save the personal information of "Zhang Sancrazy" in the array is:
copyvar arr = ['Zhang Sanfeng', 'male', 128,154];
The disadvantage of using arrays to store data in the above example is that the data can only be accessed through index values. Developers need to clearly clear the ranking of all data to obtain data accurately. When the amount of data is huge, it is impossible to memorize all the data. index value.
In order to better store a set of data, objects came into being: the attribute name is set for each item of data in the object, the data can be accessed more semantically, the data structure is clear, and the meaning is obvious, which is convenient for developers to use.
Use the object to record the last set of data as:
copyvar obj = { "name":"Zhang Sanfeng", "sex":"male", "age":128, "height":154 }
Object representation structures in JS are clearer and more powerful.
Three ways to create objects
Create objects using literals
Create objects using object literals:
copycurly braces { } It contains the properties and methods to express this specific thing (object);{ } It is expressed in the form of key-value pairs
key: equivalent to the property name
Value: equivalent to the attribute value, which can be any type of value (numeric type, string type, Boolean type, function type, etc.)
code show as below:
copyvar star = { name : 'pink', age : 18, sex : 'male', sayHi : function(){ alert('Hello everyone~'); } };
In the above code, star is the created object.
object use
properties of the object
- The "key" in the "key-value pair" that stores specific data in the object is called the attribute of the object, that is, the item that stores specific data in the object
object method
- The "key" in the "key-value pair" of the stored function in the object is called the method of the object, that is, the item of the stored function in the object
access object properties
The attribute call in the object: object. attribute name, the dot . is understood as "of"
Another way to call the properties in the object: object['property name'], note that the properties in the square brackets must be quoted
The sample code is as follows:
copyconsole.log(star.name) // call name attribute console.log(star['name']) // call name attribute
call the method of the object
The method call in the object: object. method name (), note that the method name must be followed by parentheses
The sample code is as follows:
copystar.sayHi(); // Call the sayHi method, be careful not to forget the parentheses
Summary of variables, properties, functions, methods
copyAttributes are part of the object, but variables are not part of the object, and variables are containers that store data separately
- Variable: separate declaration assignment, separate existence
- Attribute: The variables in the object are called attributes, which do not need to be declared, and are used to describe the characteristics of the object A method is a part of an object, a function is not a part of an object, a function is a container that encapsulates operations separately
- Function: It exists alone and can be called by "function name ()"
- Method: The function in the object is called a method. The method does not need to be declared, and can be called by using the method of "object. method name ()". The method is used to describe the behavior and function of the object.
Create objects with new Object
create empty object
copyvar andy = new Obect();
Create an object through the built-in constructor Object, and the andy variable has saved the created empty object at this time
Add properties and methods to empty objects
- Add properties and methods to objects by manipulating properties and methods of objects The sample code is as follows:
copyandy.name = 'pink'; andy.age = 18; andy.sex = 'male'; andy.sayHi = function(){ alert('Hello everyone~'); }
Notice:
- Object() : capitalize the first letter
- new Object() : requires the new keyword
- Format used: object.property = value;
Create objects using constructors
Constructor
Constructor: It is a special function that is mainly used to initialize objects, that is, to assign initial values to object member variables, and it is always used together with the new operator. We can extract some public properties and methods in the object, and then encapsulate them into this function.
The encapsulation format of the constructor:
copyfunction constructor name(formal parameter 1,formal parameter 2,Formal parameter 3) { this.attribute name 1 = parameter 1; this.attribute name 2 = parameter 2; this.attribute name 3 = parameter 3; this.method name = function body; }
The calling format of the constructor
copyvar obj = new constructor name(Argument 1, Argument 2, Argument 3)
In the above code, obj receives the object created by the constructor.
Precautions
- Constructor conventions are capitalized.
- The properties and methods in the function need to be added in front of this to represent the properties and methods of the current object.
- There is no need to return the result in the constructor.
- 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 into a function, which generally refers to a certain class (class) Creating an object, such as new Stars(), specifically refers to a certain one. The process of creating an object through the new keyword is also called object instantiation
The role of the new keyword
- Create an empty object before the constructor code starts executing;
- Modify the point of this to point this to the created empty object;
- code to execute the function
- After the function completes, return this—that is, the created object
5.3 Traversing objects
The for...in statement is used to loop through the properties of an array or object.
Its syntax is as follows:
copyfor (variable in object name) { // execute code here }
The variable in the grammar is self-defined, and it needs to conform to the naming convention. Usually we will write this variable as k or key.
copyfor (var k in obj) { console.log(k); // where k is the attribute name console.log(obj[k]); // Here obj[k] is the attribute value }