Small knowledge, big challenge! This paper is participating in theEssentials for programmers”Creative activities

Closure, this, scope, re validation

1.1 The concept of closures

A function declared inside a function that can access local variables of the function. Closures are functions that can read variables inside other functions.

A function that has access to a variable in another function’s scope. It’s about taking something that shouldn’t have been his.

What they do: Closures can be used in many ways. Its biggest use has two, one is to read the variables inside the function, the other is to keep the values of these variables in memory, prolong the life cycle.

1.1.3 Closure benefits and issues

Benefits:

1. You want a variable to reside in the memory for a long time

2. Avoid global variables contamination

3. The existence of private members

Question:

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.

1, occupy memory (can not timely release memory)

2. A captured variable is a reference, not a copy

3. A different closure is generated each time the parent function is called

1.1.4 Closure implementation

Implementation steps:

1. Encapsulate each function in different functions

2. Encapsulate all function functions in a self-run function, and assign the self-run function to a variable to facilitate external access to internal functions through the name of the variable.

3. There must be a return statement at the end of the self-running function, which returns each function to json data in the form of return value.

Note: This allows internal functions to be called externally as object methods.

var circle = (function(){

​        var r = 3; // A private member that cannot be accessed externally but can be called by an internal subfunction

​        function c(){

​            var result=2*Math.PI*r;

​            alert("The perimeter is :"+result);

​        }

​        function s(){

​            var result=Math.PI*r*r;

​            alert(The area is:+result);

​        }

​        return {

​            zc:c,       / / json structure

​            mj:s


​        }

​    })();

circle.zc();   / / 2

circle.mj();   / / 3
Copy the code

1.2 Garbage collection mechanism

1.2.1 Mark clearing

Tag cleanup: When the garbage collector runs, it marks all variables stored in memory. Then, it removes the tags of variables in the environment and those referenced by variables in the environment. After that, if a variable is marked again, it is ready to be deleted. Until 2008, Internet Explorer, Firefox, Opera, Chrome, and Safari javascript**** used this method;

1.2.2 Reference Counting

Reference count: Tracks how many times each value is referenced, which is the number of times a value is referenced when a variable is declared and a value of a reference type is assigned to the variable1.If this value is then assigned to another variable, the number of references is increased by one. Conversely, if a variable falls out of reference to that value, the number of references to that value is reduced by one, and when it reaches zero, it waits for the garbage collector to collect it

Note: With the exception of some very old versions of IE, most JS engines currently on the market implement garbage collection in the form of tag scavenging.

1.1.1 Variable scope

The scope within which a piece of code operates in a program – that is, the scope of a variable.

Variable scope: local variables and global variables Local variables: variables declared by var inside a function are local variables, and only all variables can be used inside the function. Variables declared outside the function are global variables, or variables not declared by var inside the function are also global variables, and the scope is the current page.

JS has no block-level scope, so use variables carefully when writing for.

Local variables cannot be read outside a functionCopy the code

Scope chain

Concept: Nested multiple functions within a function, creating a scope chain when the function accesses a variable.

Search order: Starts from the current function, if not found, the next higher level of the function, until found, if not found, the variable is undefined.

Multiple functions are nested inside a function. When the internal function accesses a variable, it starts to search from the current function. If it does not find a variable, it starts to search from the higher function until it finds it.

In short —– According to the mechanism by which internal functions can access external function variables, a chain lookup that determines which data can be accessed by internal functions is a scope chain.

3, This refers to

In the event handler, this points to —-Window

If there is an object call event — this points to the current object.

What does return false do?

1. Prevent default events

2, prevent bubbling

Exit the function

Four, regular

2.1 Syntax and concept of re

What is a regular expression? A regular expression is a logical formula used to manipulate strings. Predefined characters and their combinations form a “regular string”.

What regular expressions do: Given a regular expression and a string, we can do the following: 1. Does the given string conform to the filtering logic of the regular expression? 2. We can use the regular expression to obtain the specific part of the string we want

Regular expressions have the following characteristics: 1. Flexibility, logic and functionality; 2

Var reg=new RegExp(” expression “,” additional argument “) 2. Common var reg=/ expression/Additional parameters

1. Test () syntax: Reg.test (STR) returns true if the match is successful, false otherwise Replace () syntax str.replace(reg,” replace to character “) returns the replaced content

Metacharacters of regular expressions [0-9] digits [A-Z] letters [A-Z] Upper and lower case letters [A-Za-z] [\u4e00-\ u9FA5] Chinese Characters [0-9A-z] digits or letters [0-9A-z__] digits or letters or underscores \ W [A – z0-9 _], and \ \ W W, on the other hand, does not contain [A – z0-9 _] quite [0-9] \ d \ d \ d and contains no [0-9]

The application of regular expressions 1. Only is Chinese length is 2 to 7 / ^ ([\ u4e00 - \ u9fa5]) {2, 7} $/ 2. A string of 8 to 18 lowercase uppercase letters, digits, or underscores (_) /^[A-ZA-z0-9_]{8,18}$/ 3. Correct email format / ^ [A - Za - z0-9 \ u4e00 - \ u9fa5_] + @ [A Za - z0 - _ - 9] + (\. [A Za - z0 - _ - 9] +) + $/ 4. The correct phone number / ^ 1 (3 4 5 | | | | 7 8) \ d {9} $/ 5. The correct identification number: / ^ \ d {15} | \ d {and} ([0-9] | x) / / ^ (1-9] [0-9] {16} [0-9] x $/ 6. Correct qq number /[1-9][0-9]{4,}/ 7. Correct phone number format quantifier + contains at least one leading character? Contains 0 or 1 leading characters * Contains 0 or more leading characters. Matches any character with several dots, matches several {x} matches x leading characters {x,y} Matches x to y leading characters {x,} Matches at least x leading charactersCopy the code

Five, inheritance,

5.1 Concept of inheritance

Inheritance: Inheritance is when one object directly uses the properties and methods of another object. Inheritance gives a subclass the attributes and methods of its parent class. You don’t have to write the same code again. When a subclass inherits from its parent class, it can redefine certain properties and override certain methods.

Why inheritance?

Reduce unnecessary repetitions of code;

Higher user experience and faster loading;

5.2 Prototype chain inheritance

Methods: Prototype chain was used as follows:

Function AA(){this.uname=" "; Function BB(){} // BB constructor BB. Prototype = new AA(); Var b1 = new BB(); var b1 = new BB(); B1. uname //' Wong Tai Sin 'b1.usex //' Sir'Copy the code

1. Declare two constructors AA,BB,

2. Instantiation of AA to the prototype object assigned to BB; (Inheritance core)

3. In this way, all attributes of AA are inherited from the prototype object of BB.

4. When BB instantiates an object, the instantiated object shares all attributes of AA

Disadvantages of prototype chain inheritance:

1. When inheritance is implemented through a stereotype, the stereotype actually becomes a type instance. 2. You cannot pass functions to the constructor of a supertype

5.3 Class Inheritance (Borrowing constructors)

The class inherits as follows:

Function AA(uname){this.name=uname} function BB(){this.sex=" female "; AA. Call (this," Wu Da Wolf "); } var obj=new BB(); alert(obj.name)Copy the code

This always refers to the object on which a method is called, but using the call() and apply() methods changes the orientation of this.

call.(thisOject, arg1 ,arg2 …)

(1). Let’s talk about call() alone, because apply() is similar to call, except that the second argument to apply must be passed in an array, whereas the second argument to call can be of any type. Such as:

function add (x, y) 
{ 
    console.log (x + y);
} 
function minus (x, y) 
{ 
    console.log (x - y); 
} 
add.call (minus , 1.1);    / / 2
Copy the code

Add. Call (minus,1,1) == add(1,1), console.log (2);

(2).// Note that the js Function is actually an object and the Function name is a reference to the Function object.

A.call(B,x,y) : to run A function in B,x and y are parameters of A method.

Call is used for inheritance, and this is used to inherit all methods and properties in MyFunc1.

function myfunc1(a){
    this.name = 'Lee';
    this.myTxt = function(txt) {
        console.log( 'i am',txt ); }}function myfunc2(a){
    myfunc1.call(this);
}

var myfunc3 = new myfunc2();
myfunc3.myTxt('Geing'); // i am Geing
console.log (myfunc3.name);	// Lee
Copy the code

Advantages of class inheritance: You can pass arguments to the constructor of the parent class

Disadvantages of class inheritance: cannot inherit from a parent class.


5.4 Combination Inheritance

Inheritance through a chain of archetypes, but also through constructors, is called combinatorial inheritance

The method is as follows:

   function AA(a){
		this.name="Flower girl"
	}
AA.prototype.say = function(){

alert(this.name);

}
	function CC(a){
		AA.call(this);// Class inheritance
	}
	CC.prototype=new AA();  // Prototype chain inheritance

var cs = new CC( );

alert(cs.name)
Copy the code

Advantages: Inheritance of stereotype properties and methods using stereotype chains, and inheritance of instance properties through constructors, functions implemented by stereotype methods

The use of numbers ensures that each instance has its own attributes.

Disadvantages: In any case, the supertype constructor is called twice, once when the subtype stereotype is created and once when the subtype construct is created

Build the inside of the function.

We put js inside the common inheritance finished, summarize the three kinds of inheritance

  1. Stereotype chain inheritance, which shares reference properties
  2. Constructor inheritance, which keeps all attributes to itself, including reference attributes (emphasis on functions)
  3. Combinatorial inheritance, using the prototype chain to inherit the shared attributes, using the constructor to inherit the exclusive methods, to achieve relatively perfect inheritance

Conclusion:

The above is a beginner must know JavaScript understanding (three), the original is not easy, looking forward to your likes attention and forwarding comments 😜😜😜Copy the code