JavaScript is designed and implemented in accordance with the ECMAScript standard. The JavaScript syntax mentioned later is actually implemented in ES5 standard. JavaScript is designed and implemented in accordance with the ECMAScript standard. The JavaScript syntax mentioned later is actually implemented in ES5 standard.
What are the basic syntaxes?
01-
What are the most basic syntaxes?
The basic syntax is similar to that of almost all languages. It is nothing more than data types, operators, control statements, and functions.
5 Basic Data Types & 1 complex data type
JavaScript contains five basic data types: undefined/null/boolean/number/string. The basic data types are five. There are no other types!
JavaScript contains one complex data type, namely the Object type, which is the base class of all other objects. (Note: JavaScript does not distinguish between floating-point numbers and integers, which are expressed by number .)
The five basic data types mentioned above and one complex data type here are all the data types!
Basic Operators
This is common sense, just know what's going on.
Common operators include Arithmetic Operators, Relational operators, boolean operators, and value assignment operators.
Control statement
This is the control statement we often call such as if-else.
Not many are commonly used: if statements, switch statements, for statements, while statements, and for-in statements.
Function
A function is a small logical encapsulation. In theory, the more independent the logic, the better.
JavaScript Functions are quite different from other languages. JavaScript functions can be used as parameters or return values.
In addition, JavaScript Functions can accept any number of parameters and can access these parameters through the arguments object.
The basic syntax of any language is the same. Apart from some differences in details, it is basically the above: data types, operators, control statements, functions, modules, and so on.
Next we will introduce some more complex concepts.
02-
Variable, scope, memory problems
Variable
JavaScript variables are classified into two types: basic type and reference type. The basic type is the five basic data types mentioned above, and the reference type is the Object mentioned above and other complex data types based on it.
Basic Type: Memory occupies space of the actual size. When assigning values, a new copy is created in the memory. Stored in stack memory.
Reference Type: pointer to the object rather than the object itself. When assigning values, you only create a new pointer to the object. Stored in heap memory.
Scopes can be nested to form a scope chain. Because of the existence of the scope chain, the search for variables can be traced upwards, that is, the sub-function can access the scope of the parent function => the scope of the ancestor function => until the global scope, this type of function is also called a closure, which will be introduced later.
Var color = "blue"; function changeColor () {var anotherColor = "red"; function swapColors () {var tempColor = anotherColor; anotherColor = color; color = tempColor; // here you can access color, anotherColor, tempColor} // here you can access color and anotherColor, but you cannot access tempColor swapColors ();} // here you can only access color and changeColor ();
As shown in, variables accessible to each scope and nested scopes can be traced up.
Finally, we define the methods and attributes to be shared on the prototype, and put the methods and attributes dedicated to instances in the constructor. Here, we define a class through the 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 ("Nicolas", 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 === person2.friends); // output falsealert (person1.sayName === person2.sayName); // Output true
Implement inheritance
The previous article explains how to define a class, so we define a parent class and a subclass.
How can we make the subclass inherit the parent class? Tell you nothing else. JavaScript implements inheritance through prototype chain!
How to build a prototype chain? Assign the parent class instance to the prototype of the subclass constructor. It's good, but you have to remember it!
Prototype chain inheritance
After the prototype chain is built, the subclass can access all attributes 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;} // subclass inherits the SubType of the parent class. prototype = new SuperType (); // Add the SubType Method to the subclass. prototype. getSubValue = function () {return this. subproperty;}; // override the SubType of the parent class. prototype. getSuperValue = function () {return false ;}; // instantiate var instance = new SubType (); console. log (instance. getSuperValue (); // outputs false
Object-Oriented Knowledge can be written in a book. Here is a brief introduction to the most basic and commonly used concepts.
03-
Function expression
There are two methods for defining functions in JavaScript: function declaration and function expression. You do not need to name a function using a function expression to implement dynamic programming, that is, an anonymous function. With anonymous functions, JavaScript Functions are more powerful.
Recursion
Recursion is a common algorithm. A typical example is factorial. Let's talk about the best practice of recursion. Let's look at the Code:
// Best practice, function expression var factorial = (function f (num) {if (num <= 1) {return 1 ;} else {return num * f (num-1) ;}}); // disadvantage: // factorial may be modified // cause return num * factorial (num-1) error message: function factorial (num) {if (num <= 1) {return 1 ;}else {return num * factorial (num-1) ;}}// disadvantage: // arguments. callee, the 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 back to the function expression method. This is the best practice.
Many people think that recursion is hard to write. In fact, you can divide it into two steps to make it clearer.
Boundary condition, usually if-else.
Recursive call.
In this mode, you will be familiar with finding several typical recursive practitioners.
Closure
Many people often think that closures are complex and easy to fall into the trap. In fact, they are not.
So what is a closure? If a function can access the variables in another function scope, the former is the closure. Since JavaScript Functions can return functions, naturally, a common method to create a closure is to create another function within a function!
This is nothing magical. You can create a closure by defining a sub-function in the parent function, and the sub-function can access the scope of the parent function.
We are often scared by closures, especially a bunch of closures in the interview questions.
The definition of closure is mentioned earlier. How to Create a closure is also discussed. So let's talk about the defects of the closure and how to solve them?
/* We use subFuncs to return the function array, and then call and execute * // The returned Function Array subFuncs, these functions reference superFunc variables. // This is a typical closure. // What is the problem? // When we go back and execute the function in subFuncs, the I we get is actually 10 all the time. Why? // Because I = 10 in superFunc after subFuncs is returned, the output I is 10 when the subFuncs function is executed. /// The above is the biggest pitfall of the closure. In one sentence, the sub-function references the parent function variable, is the state function superFunc () {var subFuncs = new Array (); for (var I = 0; I <10; I ++) of the variable after the parent function ends running) {subFuncs [I] = function () {return I ;}}return subFuncs ;}// then, how can we solve the closure pit of appeal? // In fact, the principle is very simple. Since the nature of the closure pitfall is: references to the parent function variables by sub-functions, is the status of the variable after the parent function stops running. // The method for solving this problem is: The subfunction references the parent function variable, how do I use the running status? // Add self-execution based on the function expression. Function superFunc () {var subFuncs = new Array (); for (var I = 0; I <10; I ++) {subFuncs [I] = function (num) {return function () {return num ;};} (I) ;}return subFuncs ;}
In summary, the closure itself is not a complex mechanism, that is, sub-functions can access the scope of the parent function.
Because of the special nature of JavaScript Functions, we can return the function. If we will return the function as a closure function, then the parent function variable referenced by the function is the State after the parent function stops running, rather than the running status, this is the biggest pitfall of the closure. To solve this problem, we often use function expressions for self-execution.
In addition, because the closure references the scope of the ancestor function, misuse of the closure may cause memory problems.
It seems that the closure is useless. So what is the usefulness of the closure?
It's mainly encapsulation...
Encapsulation
Closures can encapsulate private variables or block-level scopes.
Volume encapsulate block-level scope
JavaScript does not have block-level scopes. It only has global scopes and function scopes. To create block-level scopes, we can use closures to simulate them.
Create and call a function immediately to encapsulate a block-level scope. This function can immediately execute the code, and the internal variable will be destroyed immediately after execution.
Function outputNumbers (count) {// In the function scope, block-level scopes are encapsulated using closures. // in this case, I is unavailable externally, then we have a block-level scope (function () {for (var I = 0; I <count; I ++) {alert (I );}})(); alert (I); // cause an error! } // In the global scope, block-level scopes are encapsulated using closures. // this way, the code block will not cause pollution to the global scope (function () {var now = new Date (); if (now. getMonth () = 0 & now. getDate () = 1) {alert ("Happy new year! ") ;}}) (); // Yes, the core of the encapsulated block-level scope is this: function expression + self-execution! (Function () {// here is the block-level scope })();
Secret encapsulate private variables
JavaScript does not have the concept of private variables. We can also use closures to implement public methods and encapsulate private variables by hiding the method of variable exposure.
(Function () {// Private variable and Private function var privateVariable = 10; function privateFunction () {return false ;}// constructor MyObject = function (){}; // public/privileged method MyObject. prototype. publicMethod = function () {privateVariable ++; return privateFunction ();};})();
03-
To sum up, what should I do?
This is almost the basic syntax and slightly more advanced usage of JavaScript. In fact, the so-called advanced is the performance of JavaScript "not very mature", especially object-oriented, for engineering purposes, JavaScript itself is not fully supported. Fortunately, the latest ES6 standard solves many problems. When used with Babel, you do not need to consider compatibility issues too much. If you are a newbie, you are advised to go directly to ES6 + Babel.
The basics of JavaScript include: 5 basic data types, 1 complex data type, operators, control statements, and functions.
After learning the basic syntax, you also need to learn about the variables, scopes, and scopes of JavaScript.
Common reference types can be used for side query. As a person, it is recommended to learn more regular expressions, which will greatly improve your code skills.
There are many external methods for Object-Oriented Programming. You just need to remember to use constructors + prototypes to define a class and use prototype chains to implement inheritance. For more extensions, go to flip the book.
Function expressions give you a few interesting things: recursion, closure, and encapsulation. Remember the best practices of recursion, the definition and defects of closures, and the applicable scenarios of closures.
JavaScript, as a dynamic language, is significantly different from other languages, which also makes it difficult for many people to learn JavaScript. But now you can look at the previous article, although it is a simple summary, but the main content of JavaScript is just like this, so don't be scared by yourself.
If you are a newbie, we suggest you go to ES6 + Babel.
More JavaScript knowledge points | from basic syntax to advanced usage articles, please pay attention to PHP Chinese network!