JavaScript foundation -- Super detail (scope and object)

cjh_ code 2021-11-25 15:14:41

JavaScript Basics -- Hyperdetail ( Arrays and functions )_m0_48651355 The blog of -CSDN Blog

Catalog

5.1 Scope  

5.1.1 Scope Overview

5.1.2 Global scope  

5.1.3 Local scope  

5.1.4   Block level scope

 5.2 Scope of variable

5.2.1 Global variables

5.2.2  local variable

5.2.3   The difference between global and local variables

5.3 Scope chain  

5.3 Pre parse  

5.3.1  Related concepts of pre parsing

5.3.2 Variable pre parsing  

5.3.3 Function pre parsing

5.3.4 The problem of function expression declaring function  

5.4 object

5.4.1 Object related concepts

5.4.2 Three ways to create objects

5.5 Traversing objects  


5.1 Scope  

5.1.1 Scope Overview

         Generally speaking , The names used in a piece of program code are not always valid and available , The scope of the code that defines the usability of the name is the scope of the name . The use of scope improves the locality of program logic , Enhance the reliability of the program , Reduced name conflicts .

JavaScript(es6 front ) There are two kinds of scopes in :

  • Global scope
  • Local scope ( Function scope )

5.1.2 Global scope  

         The environment that acts on all code execution ( Whole script The label inside ) Or an independent js file .

5.1.3 Local scope  

         Act on the code environment within the function , It's a local scope . Because it has something to do with functions , So it is also called function scope .

5.1.4   Block level scope

  • Block scope is defined by { } Include .
  • In other programming languages ( Such as java、c# etc. ), stay if sentence 、 A variable created in a loop statement , Only in Ben if sentence 、 Used in this loop statement .

java There are block-level scopes :

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

         above java The code will report an error , Because in the code { } That is, a scope , Where the declared variable num, stay “{ }” Cannot be used outside ;

         And something like that JavaScript Code , You can't report a mistake ( Only for ES6 Before the release )

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

         above JS The code can run normally ;

 5.2 Scope of variable

stay JavaScript in , Depending on the scope , Variables can be divided into two types :

  • Global variables
  • local variable

 5.2.1 Global variables

         Variables declared under the global scope are called global variables ( Variables defined outside functions ).

  • Global variables can be used anywhere in the code
  • In global scope var Declared variables are global variables
  • Under special circumstances , Don't use... In functions var Declared variables are also global variables ( Not recommended )

5.2.2  local variable

         Variables declared under local scope are called local variables ( A variable defined inside a function )

  • Local variables can only be used inside the function
  • Inside the function var The declared variable is a local variable
  • The formal parameters of a function are actually local variables

5.2.3   The difference between global and local variables

  • Global variables : It can be used anywhere , It will only be destroyed when the browser is closed , So it takes up more memory
  • local variable : Use only inside functions , When its code block is executed , Will be initialized ; After the contemporary code block runs , Will be destroyed , Therefore, it saves more memory space
var a = 10;
var b = 5;
// Declare... Outside the function body a,b And the assignment ( Global variables )
function fn(){
var b = 20; // The function is declared again and assigned as 20( local variable )
console.log(b) // The result is 20
}
fn();
console.log(a,b); // The result is 10 5

5.3 Scope chain  

         As long as the code is in a scope , The local scope written inside the function , It is not written inside any function, that is, in the global scope ; If there are functions in the function , Then a scope can be created in this scope ; According to this mechanism that external function variables can be accessed in internal functions , Use chain search to determine which data can be accessed by internal functions , It's called the scope chain

function f1() {
var num = 123;
function f2() {
console.log( num );
}
f2();
}
var num = 456;
f1();

  Scope chain : take Nearby principle To find the final value of the variable .

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 The value of is 4
console.log(b); //b Value '22'
}
}
}
fn1();

5.3 Pre parse  

5.3.1  Related concepts of pre parsing

        JavaScript The code is created by JavaScript Parser to execute .JavaScript The parser is running JavaScript There are two steps to code : Pre parsing and code execution .

  • Pre parse : Under current scope , JS Before code execution , The browser will default to include var and function Declared variables are declared or defined in memory in advance .
  • Code execution : From top to bottom JS sentence .

Pre parsing completes the declaration of variables and functions before code execution .

5.3.2 Variable pre parsing  

Pre parsing is also called variable 、 Function enhancement .
         Variable Promotion ( Variable pre parsing ): The declaration of the variable will be promoted to the top of the current scope , The assignment of variables does not increase .

console.log(num); // The result is undefined
var num = 10;
/*
js The execution of the engine
var num;
console.log(num);
num = 10;
*/

Be careful : Variable promotion only promotes declarations , No promotion assignment

5.3.3 Function pre parsing

  Function enhancement : The declaration of the function will be promoted to the top of the current scope , But it doesn't call the function .

fn();
function fn() {
console.log(' Print '); // The result is ' Print '
}

Be careful : The function declaration represents the whole function , So after the function is promoted , The function name represents the entire function , But the function is not called !    

5.3.4 The problem of function expression declaring function  

         Function expressions create functions , Will perform variable promotion , At this time, the variable name of the receiving function cannot be called correctly

fn();
var fn = function() {
console.log(' Surprised? ');// It will prompt for an error fn is not a function
}

         Before this code is executed , Can do variable declaration Promotion ,fn The value after promotion is undefined; and fn Call at fn Before being assigned to the function body , here fn The value of is undefined, So it's not possible to call  

5.4 object

5.4.1 Object related concepts

         stay JavaScript in , An object is an unordered collection of related properties and methods , All things are objects , Like strings 、 The number 、 Array 、 Functions, etc .
Objects are made up of properties and methods :

  • attribute : The characteristics of things , Use attributes to represent... In objects ( Common nouns )
  • Method : The behavior of things , Use methods to represent... In objects ( Common verbs )

  How to store a person's information ?

         Using the array :var arr = [' Zhang San ' , ' male ' , 18 , 170 ,160];

shortcoming :

  1. Data can only be retrieved through the array index value
  2. Unclear data structure , What each data represents is not clear
var obj = {
"name":" Zhang San ",
"sex":" male ",
"age":18,
"height":170,
"weight":160
}

5.4.2 Three ways to create objects

Create objects using object literals :

         It's curly braces { } It contains the expression of this specific thing ( object ) Properties and methods of ;{ } It is expressed in the form of key value pairs

var star = {
name : ' Zhang San ',
age : 18,
sex : ' male ',
sayHi : function(){
alert(' Hello, everyone ~');
}
};
//name Is the key ,' Zhang San ' Equivalent to the value 
  • key : Equivalent to property name
  • value : Equivalent to property value , Can be any type of value ( Numeric type 、 String type 、 Boolean type , Function types, etc )

  • Object to store concrete data " Key value pair " Medium " key " Properties called objects , That is, the item in the object that stores specific data
  • Object to store the function " Key value pair " Medium " key " Methods called objects , That is, the item in the object that stores the function
  • The properties in the object call : object . Property name , This little point . It means “ Of ”
  • Another way to call properties in an object : object [‘ Property name ’], Note that the attributes in square brackets must be quoted
console.log(star.name) // Call the name property
console.log(star['name']) // Call the name property 

Method of calling object :

         Object : object . Method name () , Note that the method name must be followed by parentheses

star.sayHi(); // call sayHi Method , Be careful , Make sure you don't forget the parentheses that follow 

Summary :

         Attributes are part of an object , Variables are not part of objects , Variables are containers that store data separately

  • Variable : Declare the assignment separately , Exist alone
  • attribute : The variables in the object are called properties , No declaration required , Used to describe the characteristics of the object

  Be careful : Methods are part of the object , Functions are not part of an object , Functions are containers that individually encapsulate operations

function : Existing alone , adopt “ Function name ()” You can call
Method : The functions inside the object are called methods , Methods don't need to be declared , Use “ object . Method name ()” You can call , Method is used to describe the behavior and function of the object . 

         utilize new Object Create objects :

// Create an empty object
var andy = new Obect();

Through the built-in constructor Object Create objects , here andy The variable has saved the created empty object

         Add properties and methods to empty objects

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

Be careful

  • Object() : The first letter is capitalized
  • new Object() : need new keyword
  • Format used : object . attribute = value ;

          Using constructors to create objects

Constructors : It's a special function , It's mainly used to initialize objects , That is, to assign initial values to object member variables , It's always related to new Operators . We can extract some common properties and methods from the object , Then encapsulate it into this function .

function Constructor name ( Shape parameter 1, Shape parameter 2, Shape parameter 3) {
this. Property name 1 = Parameters 1;
this. Property name 2 = Parameters 2;
this. Property name 3 = Parameters 3;
this. Method name = The body of the function ;
}

Constructor call format :

var obj = new Constructor name ( Actual parameters 1, Actual parameters 2, Actual parameters 3)

Be careful :

  1. Constructor conventions title case .
  2. Before the properties and methods in the function, you need to add this , Represents the properties and methods of the current object .
  3. In the constructor Unwanted return Return results .
  4. When we create objects , Must use new To call the constructor .

new Key role :

  1. Before the constructor code starts executing , Create an empty object ;
  2. modify this The direction of , hold this Point to the created empty object ;
  3. Code to execute functions
  4. After the function is completed , return this--- That is, the created object

5.5 Traversing objects  

for...in Statement is used to loop through the properties of an array or object .

for ( Variable in Object name ) {
// Execute the code here
}
// The variables in the syntax are custom , It needs to conform to naming conventions , Usually we will write this variable as k perhaps key.
var obj = {
name: ' Zhang San ',
age: 18,
weight:160,
height:170
}
for (var k in obj) {
console.log(k); // there k It's the property name ( namely :name、age、weight、height)
console.log(obj[k]); // there obj[k] It's property value ( namely : Zhang San 、18、160、170)
}

JavaScript Basics -- Hyperdetail ( Built in object and scope )_c.j.h_code The blog of -CSDN Blog

Please bring the original link to reprint ,thank
Similar articles

2021-11-25

2021-11-25

2021-11-25

2021-11-25

2021-11-25

2021-11-25

2021-11-25