Home > Web Front-end > JS Tutorial > Compilation of JavaScript knowledge points

Compilation of JavaScript knowledge points

高洛峰
Release: 2017-02-08 09:58:16
Original
1076 people have browsed it

JavaScript is designed and implemented in accordance with the ECMAScript standard. The JavaScript syntax mentioned later is actually the implementation of the ES5 standard.
Let’s first talk about what are the basic grammars?


What are the most basic grammars?

Basic syntax Almost all languages ​​have little difference, nothing more than data types, operators, control statements, functions, etc. Here is a brief list.


5 basic data types & 1 complex data type


JavaScript contains 5 basic data types Data types are undefined / null / boolean / number / string. These are the five basic data types, and there are no others!
JavaScript contains one complex data type, which is the Object type. The Object type is the base class of all other objects.
Note: JavaScript does not distinguish between floating point numbers and integers, they are all represented by numbers.

The 5 basic data types mentioned earlier, and the 1 complex data type here, this is all the data types!


Basic Operators


This is common sense, just know what’s going on.
Commonly used operators include: arithmetic operators, relational operators, Boolean operators, assignment operators, etc.


Control statement


This is what we often call control statements such as if-else.
There are not many commonly used ones: if statement, switch statement, for statement, while statement, for-in statement.


function


A function is an encapsulation of a small piece of logic. In theory, the more independent the logic, the better.
JavaScript functions are very different from other languages. JavaScript functions can take both parameters and return values.
In addition, JavaScript functions can accept any number of parameters, and these parameters can be accessed through the arguments object.

The basic syntax of any language is the same. Except for some detailed differences, it is roughly the above: data types, operators, control statements, functions, modules, etc.

The following introduces some slightly more complex concepts.


Variables, scope, memory issues

Variables


JavaScript variables are divided into two types : Basic types and reference types. The basic types are the five basic data types mentioned earlier, and the reference types are the Object mentioned earlier and other complex data types based on it.
✦ Basic type: occupies the actual size of space in the memory. When assigning a value, a new copy will be created in the memory. Saved in stack memory.
✦ Reference type: a pointer to an object rather than the object itself. When assigning a value, a new pointer is just created to point to the object. Saved in heap memory.

JavaScript 知识点整理

Variable memory allocation

In a word, the basic type is the actual value in the memory; while the reference type is a pointer in the memory, pointing to a Object, multiple reference types may point to the same object at the same time.

So, how to determine which data type a certain variable is?
Use the typeof operator to determine which basic type a variable is.
Use the instanceof operator to determine which reference type a variable is.
Don’t forget this!


Scope


Variables are declared in a specific scope, and the scope determines these The lifetime of variables and what code can access variables within them.
JavaScript scope only includes global scope and function scope, and does not include block-level scope!

Scopes can be nested to form a scope chain. Due to the existence of the scope chain, the search for variables can be traced upward, that is, the child function can access the scope of the parent function => the scope of the ancestor function => until the global scope. This kind of function is also called a closure. , will be introduced later.

var color = "blue"; function changeColor() { var anotherColor = "red"; function swapColors() { var tempColor = anotherColor;
anotherColor = color;
color = tempColor; / / Color, anotherColor, tempColor can be accessed here
} // Color, anotherColor can be accessed here, but tempColor cannot be accessed
swapColors();
}// Only color, changeColor();# can be accessed here

##As shown in the figure below, the variables accessible to each scope and nested scopes can be traced upward.

JavaScript 知识点整理

Scope chain

The concept of scope seems simple, but there will be many problems in actual use. If you encounter problems, you must analyze them carefully.


Memory issues


The JavaScript engine has an automatic garbage collection mechanism and does not need to pay too much attention to memory allocation and garbage collection issues. . I won’t expand on it here!


Reference type


As mentioned earlier, Object is the only complex data type, and reference types are all derived from Object Type is inherited.
✦ Array: Array type
✦ Date: Date type
✦ RegExp: Regular expression type, there are benefits to learning more about this!
✦ Wait...
Then the question comes, what data type is the function we use most? The answer is Function type!
Hey, I seem to have discovered something? Since Function is a reference type, JavaScript can add properties and methods to reference types. Well, so can functions! This is where JavaScript functions become powerful and complex. That is to say: functions can also have custom methods and properties!

In addition, JavaScript also encapsulates reference types for three of the five basic types mentioned earlier, namely Boolean, Number, and String. However, they are not used much, so you just need to understand them.

By the way, before all code is executed, two objects are built into the scope, namely Global and Math. The Global of the browser is window!

So far, the basic concepts in JavaScript have been introduced. Among them, functions and scopes are relatively complex, while others are relatively simple.
Next, I will introduce some slightly more complex concepts in JavaScript: object-oriented.


Object-oriented programming


JavaScript itself does not have the concept of classes and interfaces. Object-oriented programming is based on prototypes. realized.
For the sake of simplicity, we only analyze two object-oriented problems:
✦ How to define a class?
✦ How to implement class inheritance


Define a class

I will tell you directly without talking about anything else. We use constructor + prototype to define a class.

Use the constructor to create a custom type, and then use the new operator to create an instance of the class. However, the methods and properties on the constructor exist on every example and cannot be shared, so we introduce prototypes to achieve this. Sharing of methods and properties.

JavaScript 知识点整理

Prototype

Finally, we define the methods and properties that need to be shared on the prototype, and put the methods and properties specific to the instance in the constructor . At this point, we have defined a class through constructor + prototype.

//Constructor function Person(name, age, job) { this.name = name; this.age = age; this.job = job; this.friends = ["Shelby", "Court"];

}// Prototype Person.prototype = {
constructor: Person,
sayName: function() { return this.name;
}
}// Instantiate var person1 = new Person("Nicholas", 29, "Software Engineer");var person2 = new Person("Greg", 27, "Doctor");

person1.friends.push("Van");
Alert (Person1.friends); // Output "Shelby, Count, Van" Alert (Person2.friends); // Output "Shelby, Count" Alert (Person1.friends =====Friends); // Output falsealert(person1.sayName === person2.sayName); //Output true

Implement inheritance


The previous article talked about how to define a class , then we define a parent class and a subclass.
How to let the subclass inherit the parent class? Without further ado, I’ll tell you directly. JavaScript implements inheritance through the prototype chain!
How to build a prototype chain? Just assign the parent class instance to the prototype of the child class constructor. It’s confusing, but you must remember it!

JavaScript 知识点整理


Prototype chain inheritance

After building the prototype chain, the subclass can access all properties and methods of the parent class !

// Parent class function SuperType() { this.property = true;
}
SuperType.prototype.getSuperValue = function() { return this.property;
};// Subclass function SubType() { this.subproperty = false;
}//The subclass inherits the parent class SubType.prototype = new SuperType();//Adds a new method to the subclass SubType.prototype.getSubValue = function() { return this.subproperty;
};//Override the parent class method SubType.prototype.getSuperValue = function() { return false;
};//Instantiate var instance = new SubType();console .log(instance.getSuperValue()); //Output false

Object-oriented knowledge can be written in a book. Here is just a brief introduction to the most basic and commonly used concepts.


Function expression


There are two ways to define functions in JavaScript: function declaration and function expression.
Using function expressions does not require naming the function, thereby achieving dynamic programming, that is, anonymous functions. With anonymous functions, JavaScript functions have more powerful uses.

Recursion


Recursion is a very common algorithm, the classic example is factorial. Without talking about anything else, just talk about the best practice of recursion. The above code:

// Best practice, function expression var factorial = (function f(num) { if (num <= 1) { return 1;
} else { return num * f(num - 1);
}
});// Disadvantages: // factorial may be modified // resulting in return num * factorial( num - 1) error function factorial(num) { if (num <= 1) { return 1;
} else { return num * factorial(num - 1);
}
}// Disadvantages : // arguments.callee, the specification has deprecated the use of function factorial(num) { if (num <= 1) { return 1;
} else { return num * arguments.callee(num - 1);
}
}

Recursion is like this. Many people are still using the arguments.callee method. Change it back to the function expression method. This is the best practice.

A long-winded sentence, many people think that recursion is difficult to write, but in fact it will become much clearer if you divide it into two steps.
✦ Boundary conditions, usually if-else.
✦ Recursive call.
Follow this model, find a few classic recursions and practice them, and you will become familiar with them.

Closure


Many people often think that closures are complicated and easy to fall into pits, but this is not the case.

So what is closure? If a function can access variables in the scope of another function, then the former is a closure. Since JavaScript functions can return functions, naturally, a common way to create closures is to create another function inside a function!
There is nothing magical about this. You can create a closure by defining a child function in the parent function, and the child function can access the scope of the parent function.
We are usually frightened by closures because we are fooled by them, especially when there are a lot of closures in interview questions.

The definition of closure was mentioned earlier, and how to create a closure was also mentioned. So let’s talk about the defects of closure and how to solve them?

/* We return the function array through subFuncs, and then call and execute respectively */// Return the array subFuncs of the function, and these functions have references to the variables of superFunc // This is a typical closure // So what is the problem Woolen cloth? // When we go back and execute the function in subFuncs, the i we get is actually always 10. Why? // Because when we return subFuncs, i=10 in superFunc // So when the function in subFuncs is executed, the output i is 10. // // The above is the biggest pitfall of closures. To understand it in one sentence: // The reference of the sub-function to the parent function variable is the state of the variable after the parent function finishes running function superFunc() { var subFuncs = new Array( ); for (var i = 0; i < 10; i++) {
subFuncs[i] = function() { return i;
};
} return subFuncs;
}// So, how to solve the closure pit of appeal? // In fact, the principle is very simple. Since the essence of the closure pit is: the reference of the child function to the parent function variable is the state of the variable after the parent function finishes running // Then the way we solve this problem is: the child function references the parent function Variable reference, use runtime state // How to do this? //On the basis of function expression, just add self-execution. function superFunc() { var subFuncs = new Array(); for (var i = 0; i < 10; i++) {
## ; The scope of the function.
Due to the particularity of JavaScript functions, we can return functions. If we return a function as a closure, then the parent function variable referenced by the function is the state after the parent function finishes running, not the state at runtime. This is the biggest pitfall of closures. In order to solve this pitfall, our common way is to make function expressions self-execute.
In addition, because closures refer to the scope of ancestor functions, there will be memory problems when abusing closures.

It seems that closure is useless, so what is the use of closure?
Mainly encapsulation...

Encapsulation


Closure can encapsulate private variables or encapsulate block-level scope.

➙ Encapsulating block-level scope

JavaScript does not have the concept of block-level scope, only global scope and function scope. If we want to create a block-level scope, we can simulate it through closure.

Create and immediately call a function to encapsulate a block-level scope. This function can execute the code in it immediately, and the internal variables will be destroyed immediately after execution.


function outputNumbers(count) { // In the function scope, use closure to encapsulate the block-level scope

// In this case, i is not available externally, and there will be a similar block-level scope

(function() { for (var i = 0; i < count; i++) {
alert(i);
}
})();

alert (i); //Cause an error! }//In the global scope, use closures to encapsulate the block-level scope//In this way, the code block will not pollute the global scope (function() { var now = new Date(); if (now.getMonth() == 0 && now.getDate() == 1) {
alert("Happy new year!");
}
})() ;// Yes, the core of encapsulating block-level scope is this: function expression + self-execution! (function() { //This is the block-level scope})();


➙ Encapsulating private variables
JavaScript does not have the concept of private variables, we can also use closures to achieve this Public methods encapsulate private variables by hiding variables and exposing methods.

(function() { //Private variables and private functions
var privateVariable = 10; function privateFunction() { return false;
} } //Constructor

MyObject = function() {}; //Public/privileged method

MyObject.prototype.publicMethod = function() {
privateVariable++; return privateFunction();

};

})();


What should you say in conclusion?

This is almost some basic syntax and slightly more advanced usage of JavaScript. In fact, the so-called advanced are manifestations of JavaScript's "immature", especially object-oriented, for engineering needs, but JavaScript itself is not Perfect support. Fortunately, the latest ES6 standard has solved many problems, and you don’t have to worry too much about compatibility when using it with Babel. If you are a novice, I suggest you go directly to ES6+Babel.

✦ The foundation of JavaScript mainly includes: 5 basic data types, 1 complex data type, operators, control statements, functions, etc.
✦ After understanding the basic syntax, you also need to learn JavaScript variables, scope, and scope chain.
✦ Common reference types can be checked and used. As someone who has experienced it, I suggest you learn more rules, which will greatly improve your coding skills.
✦ There are many ways to do object-oriented programming. You just need to remember to use constructor + prototype to define a class, and use the prototype chain to implement inheritance. For more extensions, go read the book.
✦ Function expressions lead to several interesting things: recursion, closure, and encapsulation. Remember the best practices of recursion, the definition and pitfalls of closure, and the applicable scenarios of closure.

As a dynamic language, JavaScript is quite different from other languages, which also causes many people to find it difficult to learn JavaScript. But if you look at the previous article now, although it is a brief summary, this is the main content of JavaScript, so don’t be scared by yourself.
One more thing, if you are a newbie, I suggest you go directly to ES6+Babel.

For more JavaScript knowledge points related articles, please pay attention to the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template