LiNPX zh-CN Linpx is a personal blog, of course, the content is mainly biased towards programmers and the Internet, most of which are personal learning and reminders. Of course, there are some other tutorials and some opinions. I hope that I can help you as I grow up Sun, 24 Apr 2016 15:46:00 +0800 Sun, 24 Apr 2016 15:46:00 +0800 Some of the Typecho plug-ins I'm using right now Sun, 24 Apr 2016 15:46:00 +0800 Chakhsu Lau This is a suggestion for some plug-ins using my theme

to update

27 August 2016:
Replace commentfilter with smartspam

Plug ins in use

Typecho automatic translation slug plug-in

Commenttomail comment email reminder plugin

Google sitemap builder

Typecho cache plug in for_ typecho.html

Some introduction

In use Lpisme At the same time, there is no conflict in the use of these plug-ins. You can rest assured that they can be used together with the theme. In addition, the code design of the theme is lightweight, no JQ, no front-end framework, fast loading, and faster with CDN. Moreover, the use of these plug-ins will not affect the loading of web pages like some plug-ins of WP.

The theme uses two small JS libraries, especially the prismjs code. It can be modified according to your own needs. The modification method is the same as the official website document. The other is instantclickjs, which is used to speed up the loading of web pages. If there is a conflict in the test, you can turn it off in the background appearance settings.

On the issue of comment spam filtering, it is recommended to close the background and replace this function with a plug-in.


If you have something you're using, a better plug-in would like to leave a recommendation in the comments^^

Notes on learning UML class diagram Fri, 22 Apr 2016 06:41:00 +0800 Chakhsu Lau Diagram and class are important to understand the relationship between system design and class, and it is also an important basis for system design and analysis.


Class encapsulates data and behavior. It is an important part of object-oriented. It is the general name of object collection with the same attributes, operations and relationships. In the system, each class has a certain responsibility, which refers to what kind of functions and obligations the class should undertake. A class can have multiple responsibilities. A well-designed class usually has only one responsibility. When defining a class, the responsibilities of a class are decomposed into its attributes and operations (that is, methods). The attribute of a class is the data responsibility of a class, and the operation of a class is the behavior responsibility of a class. Design class is the most important part of object-oriented design, and also the most complex and time-consuming part.

When the software system is running, the class will be instantiated into an object. The object corresponds to a specific thing, which is an instance of the class.

Class diagram describes the static structure of a system by using different classes that appear in the system. It is used to describe different classes and their relationships.

In the system analysis and design stage, classes can be generally divided into three types, namely entity class, control class and boundary class

(1) Entity class: the entity class corresponds to each entity in the system requirements. They usually need to be stored in the permanent storage, and are usually recorded by database tables or files. The entity class includes not only the class for storing and transferring data, but also the class for operating data. Entity class comes from nouns in requirement specification, such as student, commodity, etc.

(2) It can be used to reduce the control degree between the application classes and control classes. Control class is a noun transformed from verb object phrase (verb + noun). For example, adding goods corresponds to a product adding class, and registration corresponds to a user registration class.

(3) Boundary class: boundary class is used to abstract the interaction objects between external users and the system, mainly including interface classes, such as dialog box, window, menu, etc.

In the primary stage of object-oriented analysis and design, entity classes are usually identified first and the initial class diagram is drawn. At this time, the class diagram can also be called domain model, including entity classes and their relationships.

Class relations

  • Generalization

  • Realize relationship

  • Aggregation

  • Composition

  • Association

  • Dependency

Generalization relation

The inheritance structure of class is shown in UML as: generalize and realize:

The relationship between - is and is can be expressed as an inheritance relation

Eg: bicycles are cars and cats are animals

The generalization relation is directly represented by a hollow arrow, as shown in the figure below (a inherits from b);


Note: in the final code, the generalization relation is shown to inherit non abstract classes

Realizing relationships

The realization relationship is represented by a dotted line with a hollow arrow;

Eg: "car" is an abstract concept, which can't be used to define objects directly in reality. Only when a specific subclass (car or bicycle) is specified can it be used to define objects (car class is represented by abstract class in C + + and interface concept in Java is easier to understand)


Finally, the inheritance relation is represented by abstract code

Aggregation relation

The aggregation relationship is represented by a straight line with a hollow diamond arrow, as shown in the figure below, which shows that a is aggregated onto B, or B is composed of A


Aggregation relation is used to represent the relationship between entity objects, and to represent the semantics of the whole consisting of parts. For example, a department is composed of multiple employees;

Different from the combination relationship, the whole and the part are not strongly dependent, even if the whole does not exist, the part still exists; for example, if the Department is cancelled, the personnel will not disappear, but they still exist;

synthetic relation

The combination relationship is represented by a straight line with a solid diamond shaped arrow, as shown in the figure below, which indicates that a constitutes B, or B consists of A;


Like aggregation relation, combination relation also means the semantics that the whole is composed of parts;

However, the combination relationship is a special aggregation relationship with strong dependence. If the whole does not exist, then some parts will not exist; for example, if the company does not exist, the Department will not exist;


Association is represented by a straight line; it describes the structural relationship between different classes of objects; it is a static relationship, which is usually independent of the running state, and is generally determined by common sense and other factors; it is generally used to define the static and natural structure between objects; therefore, association relationship is a kind of "strong association" relationship;

For example, there is an association between passengers and tickets, students and schools;

By default, association does not emphasize direction, which means that objects know each other. If the direction is particularly emphasized, it means that a knows B, but B does not know a;


Note: in the final code, association objects are usually implemented in the form of member variables;


Dependency is represented by a set of dashed lines with arrows. The figure below shows that a depends on B. It describes the relationship between an object and another object during its operation;


Different from the association relationship, it is a temporary relationship, which usually occurs during the runtime and changes with the runtime;

Obviously, dependence also has direction. Bidirectional dependence is a very bad structure. We should always keep one-way dependence and put an end to it;

Note: in the final code, the dependency relationship is reflected as the class construction method and the input parameters of the class method, and the arrow is the calling relationship; the dependency processing temporarily knows whether to "use" the other party's methods and properties outside of the other party;

reference resources CN/latest/read_ uml.html

Notes on learning sequence diagrams Fri, 22 Apr 2016 06:08:00 +0800 Chakhsu Lau Sequence diagram, also known as sequence diagram or sequence diagram, is a kind of UML behavior diagram. It shows the dynamic cooperation among multiple objects by describing the time sequence of sending messages between objects. When a use case behavior is executed, each message in the sequence diagram corresponds to a class operation or a trigger event that causes a transition in the state machine. via: wiki

brief introduction

Sequence diagram definition: describes the time sequence of messages between objects, which is used to represent the behavior sequence in use cases, and is an interaction diagram that emphasizes the time sequence of messages

Things described by sequence diagram: sequence diagram describes the interaction between classes in the system, modeling these interactions as message exchange. Sequence diagram describes the class and the message of expected behavior completed by the exchange between classes. Each message in the sequence diagram represents an operation of a class or a trigger event that causes the state machine to change

Sequence diagram representation: the objects participating in the interaction are arranged horizontally at the top of the sequence diagram, and a vertical dotted line is drawn at the bottom of each object. Object a sends messages like object B and is represented by a solid line with an arrow. The solid line starts from the dotted line at the bottom of object a and ends at the dotted line at the bottom of object B. the solid line arrow is horizontally placed, and the closer it is to the top, the earlier it is sent

Sequence diagram trace: the sequence diagram provides a clear and visual trace over time

Sequence Diagram Elements

The modeling elements included in the sequence diagram are: object, lifeline, activation, message, etc


Object: the role of an object in a sequence diagram in an interaction is an object

Symbols of objects: objects in sequence diagrams are represented in the same way as objects in object diagrams. Rectangles are used to contain object names, and the object names are underlined

When to create an object: the object can be created at the beginning of the interaction or during the interaction process

  • At top: if the object is at the top of the sequence diagram, the object already exists at the beginning of the interaction

  • Not on top: if the position of the object is not at the top, the object is created during the interaction


Lifeline: a lifeline is a vertical dashed line that indicates the existence of an object. In the sequence diagram, there is a lifeline at the bottom of each object

Lifeline effect: a lifeline is a timeline that exists from the top to the bottom of the sequence diagram, and its length depends on the time of the interaction

Lifeline of object: the lifeline of an object is the lifeline of an object when it is combined with an object. This concept includes the object icon and the lifeline icon below the object


Activation: represents the time when an object in the sequence diagram performs an operation. The activation period can be understood as the content in {} in semantics, indicating that the object is occupied to complete a task

Deactivation: when an object is idle and waiting for a message to activate the object

Active representation: when the object is active, the lifeline can be expanded to a rectangle, which becomes the active bar

Time of activation and deactivation:

  • Activation: object activation is activated at the top of the activation bar

  • Deactivation: deactivation at the bottom of the activation bar, usually when a message leaves the object lifeline


Message concept: define the class of exchanging information in interaction and collaboration, and model the communication content between objects

Message action:

  • Action types: messages allow information (transfer parameters) to be passed between entities, entities are allowed to request other services, and objects communicate by sending and receiving messages;

  • Produce results: messages can trigger operations, raise signals, or cause the target object to be created or destroyed

Asynchronous and synchronous communication of messages:

  • Asynchronous communication: when a message is a signal, wait for the other party to trigger the corresponding method after sending the signal. This is asynchronous communication between explicitly named objects

  • Synchronous communication: call the method of the object directly, execute the method and return the result. This operation with return control mechanism is synchronous communication

The difference between sequence diagram and collaboration diagram is that messages in sequence diagram emphasize order, while messages in collaboration diagram emphasize the relationship between objects exchanging messages

reference resources CN/latest/read_ uml.html

Operators for JavaScript Wed, 06 Apr 2016 11:12:00 +0800 Chakhsu Lau JavaScript has the following types of operators

  • Assignment operators

  • Comparison operators

  • Arithmetic operators

  • Bitwise operators

  • Logical operators

  • String operators

  • Conditional operator

  • Comma operator

  • Unary operators

  • Relational operator

JavaScript has binary and unary operators, and a special ternary operator (conditional operator)

Assignment Operators

An assignment operator assigns a value based on the value of its right-hand operands to its left-hand operands

name shorthand Equivalent to
assignment Assignment x = y , x = y
Additive assignment Addition assignment x += y , x = x + y
Subtraction assignment Subtraction assignment x -= y , x = x - y
Multiplicative assignment Multiplication assignment x *= y , x = x * y
division assignment Division assignment x /= y , x = x / y
Co assignment Remainder assignment x %= y , x = x % y
Power assignment Exponentiation assignment x **= y , x = x ** y
Left shift assignment Left shift assignment x <<= y , x = x << y
Right shift assignment Right shift assignment x >>= y , x = x >> y
Signed right shift assignment Unsigned right shift assignment x >>>= y , x = x >>> y
Bitwise and assignment Bitwise AND assignment x &= y , x = x & y
bitwise XOR assignment Bitwise XOR assignment x ^= y , x = x ^ y
bitwise OR assignment Bitwise OR assignment x \ = y , x = x\ y


Deconstruction assignment designing assignment syntax is a JavaScript expression that can extract data from array or object corresponding array structure or object literal

 Var foo = ["one", "two", "three"]; 
 / / do not use deconstruction 
 var one = foo [0]; 
 var two = foo [1]; 
 / / use deconstruction 
 var [one, two, three] = foo;

Comparison operator

A comparison operator compares its operands and returns a logical value of whether the opportunity expression is true

Operands can be numbers, strings, logic, object values

The following table describes the comparison operators in the sample code

 var var1 = 3, var2 = 4;
operator describe An example that returns true
Equal (= =) Returns true if both operands are equal 3 == var1 , "3" == var1 , 3 == '3'
Not equal to not equal (! =) Returns true if the operands on both sides are not equal var1 != 4 , var2 != "3"
Strict equal (= = = =) Returns true when the operands on both sides are equal and of the same type 3 === var1
Strict not equal (! = =) Returns true when the operands on both sides are not equal or of different types var1 !== "3" , 3 !== '3'
Greater than (>) The operands on the left are greater than those on the right. Return true var2 > var1 , "12" > 2
Greater than or equal (> =) The operands on the left are greater than or equal to the operands on the right and return true var2 >= var1 , var1 >= 3
< less than The operands on the left are less than those on the right. Return true var1 < var2 , "2" < 12
Less than or equal (< =) The operands on the left are less than or equal to those on the right, and return true var1 <= var2 , var2 <= 5

Arithmetic operator

An arithmetic operator takes a numeric value (literal or variable) as its operands and returns a numeric value. The standard arithmetic operator is addition, subtraction, multiplication, and division (+ - * /)

 console.log(1 / 2); /* prints 0.5 */
console.log(1 / 2 == 1.0 / 2.0); /* also this is true */
operator describe Examples
%(for remainder) Binary operator. Returns the remainder after division 13% 5 return 3
++(self increasing) Unary operator. Adds one to the value of the operands var x=3; console.log(++x); console.log(x);var y=3; console.log(y++); console.log(y); //4434
--(self reduction) Unary operator. Subtracts the value of the operands by one var x=3; console.log(--x); var y=3; console.log(y--);
-(unary negative) Unary operator that returns the negative value of the operands Var x = 3; console.log (- x); / / enter - 3
+(unary positive sign) Unary operator that returns the positive value of the operands console.log( +'3' ); console.log( '3' ); console.log(+true); //3 '3' 1

Bitwise Operators

It is a binary or 8-bit string rather than a decimal operator

For example, the decimal number 9 is represented in binary as 1001, and the bit operator performs the operation on this binary representation, but the return result is a standard JavaScript value

Bit logic operator

expression result Binary description
15 & 9 nine 1111 & 1001 = 1001
15.9 fifteen 1111 1001 = 1111
15 ^ 9 six 1111 ^ 1001 = 0110
~15 -16 ~00000000...00001111 = 11111111...11110000
~9 -10 ~00000000...00001001 = 11111111...11110110

Shift Operators

The shift operator has two operands:

  • Number to be shifted

  • A number that specifies how many bits the first number should be moved

The direction of the shift is controlled by the operator

operator describe
< < (left shift) Moves the first operand to the left by a specified number of bits. The left out bits are discarded. The left shifted bits are discarded. The extra bits on the right are supplemented by 0
>>(shift right with sign) The number of digits left of the first digit to be moved to the left by the left
>>>(zero padding, right shift) Moves the first operand to the right by a specified number of bits. The right out bit is discarded. The left extra space is filled by 0

Logical operator

Logical operators are often used between Boolean (logical) values

When all operands are Boolean, the return value is also Boolean

Here is && Examples of (logical and) operators

 var a1 =  true && true;     // t && t returns true
var a2 =  true && false;    // t && f returns false
var a3 = false && true;     // f && t returns false
var a4 = false && (3 == 4); // f && f returns false
var a5 = "Cat" && "Dog";    // t && t returns Dog
var a6 = false && "Cat";    // f && t returns false
var a7 = "Cat" && false;     // t && f returns false

Here is || Examples of (logical or) operators

 var o1 =  true || true;     // t || t returns true
var o2 = false || true;     // f || t returns true
var o3 =  true || false;    // t || f returns true
var o4 = false || (3 == 4); // f || f returns false
var o5 = "Cat" || "Dog";    // t || t returns Cat
var o6 = false || "Cat";    // f || t returns Cat
var o7 = "Cat" || false;     // t || f returns Cat

Here is Examples of (logical not) operators

 var n1 = !true;  // !t returns false
var n2 = !false; // !f returns true
var n3 = !"Cat"; // !t returns false

String operator


 console.log( "my " + "string " + 2); // "my string 2"

(+ =) in series

 var myString = "alpha";
myString += "bet";

Conditional (ternary) operator

The conditional operator is the only operator in JavaScript that requires three operands

The result of the operation takes one of the two values according to the given conditions

 condition ? val1 : val2

If condition is true, the result is val1, otherwise it is val2

 var status = (age >= 18) ? "adult" : "minor";

When age is greater than or equal to 18, the statement will "adult" Assign to status, otherwise the "minor" Assign to status

comma operator

The comma operator evaluates two operands and returns the value of the second

It is often used in for loops to update multiple variables at each loop

 for (var i = 0, j = 9; i <= j; i++, j--)
  console.log("a[" + i + "][" + j + "]= " + a[i][j]);
 a = b = 3, c = 4; // Returns 4 in console
console.log(a); // 3 (left-most)

x = (y = 5, z = 6); // Returns 6 in console
console.log(x); // 6 (right-most)

unary operator

A unary operator corresponds to only one operand

Delete operator

Delete operator to delete an object or an object's property or an element at a specified index in an array

 delete objectName;
delete objectName[index];
delete property; // legal only within a with statement

If the delete operation is successful, the attribute or element will become undefined. If delete is feasible, it will return true, if not, it will return false

 x = 42;
var y = 43;
myobj = new Number();
myobj.h = 4;    // create property h
delete x;       // returns true (can delete if declared implicitly)
delete y;       // returns false (cannot delete if declared with var)
delete Math.PI; // returns false (cannot delete predefined properties)
delete myobj.h;  // returns true (can delete user-defined properties)
delete myobj;   // returns true (can delete if declared implicitly)

also typeof void

Relational operators

In operator

True is returned if the specified property is in the specified object

 propNameOrNumber in objectName

Common usage of in operation

 // Arrays
var trees = new Array("redwood", "bay", "cedar", "oak", "maple");
0 in trees;        // returns true
3 in trees;        // returns true
6 in trees;        // returns false
"bay" in trees;    // returns false (you must specify the index number,
                   // not the value at that index)
"length" in trees;  // returns true (length is an Array property)

// Predefined objects
"PI" in Math;          // returns true
var myString = new String("coral");
"length" in myString;  // returns true

// Custom objects
var mycar = {make: "Honda", model: "Accord", year: 1998};
"make" in mycar;  // returns true
"model" in mycar; // returns true

Reading materials:

Review method: Practice (code write once, run once, test once), Google where you don't understand, read and take notes

Bottom line principle: you'd rather rewrite it once than copy and paste it

This review content has: operator···

Review time: off and on for a few days... I am also drunk···

JavaScript closure and arrow function Wed, 06 Apr 2016 10:41:00 +0800 Chakhsu Lau closure

Closures are one of the most powerful features in JavaScript

JavaScript allows function nesting

Internal functions can access all variables and functions defined in external functions and all variables and functions that external functions can access

External functions cannot access variables and functions defined in internal functions

When the life cycle of the inner function is longer than that of the outer function, because the inner function can access the scope of the external function, the life cycle of the variables and functions defined in the external function will be longer than the external function itself

When an inner function is accessed in some way by any external function scope, a closure And that's what happened

 var pet = function(name) {   // The outer function defines a variable called "name"
  var getName = function() {
    return name;             // The inner function has access to the "name" variable of the outer function
  return getName;            // Return the inner function, thereby exposing it to outer scopes
myPet = pet("Vivie"); 
myPet();                     // Returns "Vivie"

In this example, the following function can return an internal operation

 var createPet = function(name) {
  var sex;
  return {
    setName: function(newName) {
      name = newName;
    getName: function() {
      return name;
    getSex: function() {
      return sex;
    setSex: function(newSex) {
      if(typeof newSex == "string" 
        && (newSex.toLowerCase() == "male" ||  newSex.toLowerCase() == "female")) {
        sex = newSex;

var pet = createPet("Vivie");
pet.getName();                  // Vivie

pet.getSex();                   // male
pet.getName();                  // Oliver

An embedded variable of an embedded function is like a safe for an embedded function. They keep "stable" - and safe -- data for embedded functions to run. These embedded functions don't even have to be assigned to a variable, or they don't have to have a name.

 var getCode = (function(){
  var secureCode = "0]Eal(eh&2";    // A code we do not want outsiders to be able to modify...
  return function () {
    return secureCode;

getCode();    // Returns the secret code

be careful : if a closed function defines the same variable with the variable name of the external function, it can no longer point to the variable in the external function field.

 var createPet = function(name) {  // Outer function defines a variable called "name"
  return {
    setName: function(name) {    // Enclosed function also defines a variable called "name"
      name = name;               // ??? How do we access the "name" defined by the outer function ???

The magic variable this in a closure is very weird.
It depends very much on where this is called, not exactly where it is defined.

Using the arguments object

The actual arguments to the function are saved in an array like arguments object. Within the function, you can find the arguments passed in as follows:

  • Where I is the ordinal number of the argument, starting with 0

  • The first parameter will be arguments [0]

  • The number of parameters is represented by arguments. Length

For example, imagine a function that connects strings. The only pre-determined parameter is the character used to separate the connected parts in the concatenated string. This function is defined as follows:

 function myConcat(separator) {
   var result = "", // initialize list
   // iterate through arguments
   for (i = 1; i < arguments.length; i++) {
      result += arguments[i] + separator;
   return result;

You can pass any number of arguments to this function, which concatenates the parameters into a string "list":

 // returns "red, orange, blue, "
myConcat(", ", "red", "orange", "blue");

// returns "elephant; giraffe; lion; cheetah; "
myConcat("; ", "elephant", "giraffe", "lion", "cheetah");

// returns "sage. basil. oregano. pepper. parsley. "
myConcat(". ", "sage", "basil", "oregano", "pepper", "parsley");

be careful

  • Arguments variable is just a "class array object", not an array

  • Called a class array object, it has an index number and a length property

  • It does not have all the operation methods of array objects

Function parameters

Two new types of parameters:

  • Default parameters

  • Rest parameters

Default parameters

In JavaScript, the default value of the function parameter is undefined

 function multiply(a, b) {
  b = typeof b !== 'undefined' ?  b : 1;

  return a*b;

multiply(5); // 5

When calling a function, there is no argument passed to B, then its value is undefined. Therefore, after calculating a * B, the function returns Nan

Residual parameters

The remainder parameter syntax allows an indefinite number of parameters to be represented as an array

 function multiply(multiplier, ...theArgs) {
  return => multiplier * x);

var arr = multiply(2, 1, 2, 3);
console.log(arr); // [2, 4, 6]

Arrow function

Arrow function expressions (also known as fat arrow functions) have a shorter syntax than function expressions and lexical binding to this value. Arrow functions are always anonymous.

There are two factors that affect the introduction of arrow functions:

  • Simpler functions

  • this

Simpler functions

 var a = [
var a2 ={ return s.length });
var a3 = s => s.length );


Before the arrow function appeared, each new function redefined its own this value (in strict mode, a new object is undefined in the constructor, the function called by the context object is called "object method", etc.)

 function Person() {
  // The Person() constructor defines `this` as itself.
  this.age = 0;

  setInterval(function growUp() {
    // In nonstrict mode, the growUp() function defines `this` 
    // as the global object, which is different from the `this`
    // defined by the Person() constructor.
  }, 1000);
var p = new Person();

In ECMAScript 3 / 5, this problem can be fixed by assigning the value of this to a variable

 function Person() {
  var self = this; // Some choose `that` instead of `self`. 
                   // Choose one and be consistent.
  self.age = 0;

  setInterval(function growUp() {
    // The callback refers to the `self` variable of which
    // the value is the expected object.
  }, 1000);

In addition, creating a bound function enables this value to be passed correctly to the growth() function

The arrow function captures the this value of the closure context, so the following code works

 function Person(){
  this.age = 0;
  setInterval(() => {
    this.age++; // |this| properly refers to the person object
  }, 1000);
var p = new Person();

Reading materials:

Review method: Practice (code write once, run once, test once), Google where you don't understand, read and take notes

The bottom line: better copy than paste

The content of this review is: the latter part of the function···

Review time: off and on for a few days... I am also drunk···

JavaScript functions Sun, 27 Mar 2016 01:04:00 +0800 Chakhsu Lau Defining functions

The definition of a function (also known as a function declaration) consists of a series of function keywords

  • The name of the function

  • A list of function arguments enclosed in brackets () and enclosed by commas , division

  • Function function, surrounded by curly brackets {}, is used to define the function of some JavaScript statements

for example

 function square(number) {
  return number * number;

The function square takes a single parameter called number
This function has only one statement, which indicates that the function will multiply the function parameter (i.e. number) and return it
The return statement of the function determines the return value of the function

If you pass an object as an argument, and the function changes the properties of the object, the change is visible outside the function

 Goal myfunc (theoobject) {theobject.make = Toyota '; 
 var mycar = {make: "Honda", "model:" accord ", year: 1998}, 
 var x, y, y; 
 x = mycar.make; / / x gets the value of" Honda "
 (myfunc (mycar); 
 y = mycard.make; / / y gets the value of" Toyota "; / / (make attribute's attribute's value is" Toyota "/ / (make attribute's make attribute's make attribute's" Toyota "/ / (make attribute's make attribute's make attribute's" Toyota "/ / / / (make attribute's make attribute's make attribute's" make attribute's "make attribute's the value is changed in the function)

Function expression

 The value of {var = 10} is obtained by {var = 10}

A function expression can also provide a function name, which is used inside a function to refer to itself

 var factorial = function fac(n) {return n<2 ? 1 : n*fac(n-1)};

Function expression is very convenient to pass function as an argument to other functions

The following example shows how a function called map is defined and an anonymous function is called as its first parameter

 Function map (F, a) {var result = [], / / create a new array 
 for (I = 0; I! = a.length; I + +) 
 result [i] = f (a [i]); 
 return result; 
} map (function (x) {return x * x * x}, [0, 1, 2, 5, 10]); / / return [0, 1, 8, 125, 1000]

Define a function based on conditions, such as the following example

 var myFunc;
if (num == 0){
  myFunc = function(theObject) {
    theObject.make = "Toyota"

When an object's property is a function, it is called a method

Call function

These functions are actually called to perform the actions given

For example, with the function square defined, you can call it as follows


Functions must be in the domain in which they are called, but functions can be declared after their calling statements, such as

/* ... */
function square(n) { return n*n }

A function field is where a function is declared, or the entire program when a function is declared at the top level

Meaning only uses the above grammatical form function funcName(){} The following example is invalid

 console.log(square(5)); // square is not defined
square = function (n) {
  return n * n;

A function can be recursive; that is, a function can call itself. The following example calculates the factorial value of recursion

 If (n = = 0) | (n = = 1) | (n = = 1)), return 1; else @ return return (n * factorial (n - 1)); 
, var a, B, C, C, D, E; 
a = factorial (1); / / 1 assigned to a 
 B = factorial (2); / / 2 assigned the value to B = C = factorial (3); / / 6 assigned the value to C = C = factorial (3); / / 6 assigned the value to C = D = D = D (3); / / 6 assigned the value to C = D = D = 3); / / 6 assigned the value to C = C = C = C = factorial (3); / / 6 assigned the value to C < C = C = C = C = C factorial (4); / / 24 is assigned to d
e = factorial (5); / / 120 is assigned to E

Scope of function

A function can take any variable and subfunction defined in its domain

  • Functions defined in the global domain can obtain all variables defined in the global domain

  • A child function defined within a function can take any variable defined in its parent function or acquired by its parent function

 //The following variables are defined in the global scope domain 
 var num1 = 20, 
 num2 = 3, 
 name = chamahk ";;; 
 / / this function defines in global scope 
 function multiply() {return return return num1 * num1 * num2; 
} multiply(); / / returns returns 60 
 / / returns 60 
 / / the example of the nested function 
 function getscore(); {var num1 = 2, 
num2 = 2, 
 num2 = 3; 
;;;;;; / / the function defines the example of the nested function, 
 function getscore() (); {var num1 = 2, 

function add() {return name +" scored "  + (num1 + num2);
  return add();
getScore(); // Returns "Chamahk scored 5"

Scope and function stack


Functions can point to and call itself. There are three ways to call itself

  1. By using the function's name

  2. Use arguments. Call (ECMAScript (Es5) forbids use of arguments. Call() in strict mode)

  3. An in scope variable references to the function

Function definition:

 var foo = function bar() {
   // statements go here

In the body of this function, the following statements are equivalent

  • bar()

  • arguments.callee()

  • foo()

Our recursive function is called recursive function

In a sense, recursion is similar to a loop
Both repeat the same code, and both require a termination condition to avoid infinite loops or infinite recursion

 var x = 0;
while (x < 10) { // "x < 10" is the loop condition
   // do stuff

Convert to a recursive function and call to it

 function loop(x) {
  if (x >= 10) // "x >= 10" is the exit condition (equivalent to "!(x < 10)")
  // do stuff
  loop(x + 1); // the recursive call

Some algorithms can't be implemented simply by loop. For example, it is much easier to implement recursion when you get all the nodes in the tree structure

 function walkTree(node) {
  if (node == null) // 
  // do something with node
  for (var i = 0; i < node.childNodes.length; i++) {

Each recursive call here produces more recursion than a loop function

In fact, recursive functions use the stack: the function stack

 function foo(i) {
  if (i < 0)
  console.log('begin:' + i);
  foo(i - 1);
  console.log('end:' + i);

// Output:

// begin:3
// begin:2
// begin:1
// begin:0
// end:0
// end:1
// end:2
// end:3

Nested functions and closures

Nesting another function within one function
Nested functions are private members of container functions. It also forms a closure of itself
Usually, an environment variable can have its own closure

A nested function is a closure, which means that a nested function can inherit the parameters and variables of the container function. In other words, the inner function contains the scope of the outer function.

  • Internal functions can only be accessed in external functions

  • But it can't use the outer variable and the outer parameter of the function

Nested functions:

 function addSquares(a,b) {
  function square(x) {
    return x * x;
  return square(a) + square(b);
a = addSquares(2,3); // returns 13
b = addSquares(3,4); // returns 25
c = addSquares(4,5); // returns 41

The inner function forms a closure, and you can call the outer function and specify the parameters of the outer and inner functions

 function outside(x) {
  function inside(y) {
    return x + y;
  return inside;
// Think of it like: give me a function that adds 3 to whatever you give it
fn_ inside = outside(3); 
result = fn_ inside(5); // returns 8
result1 = outside(3)(5); // returns 8

Save variables

A closure must hold all parameters and variables in its visible scope
The parameters passed in may be different for each call, and each call to an external function actually recreates the closure
Memory is released only when the return value of inside is no longer referenced

Multi level nested functions

Functions can be nested in multiple layers

For example, function a can contain function B, and function B can contain function C. Both B and C form closures, so B can access a, and C can access B and a

Closures can contain multiple scopes, and they recursively include all the function scopes that contain it. This chain is called the scope

 function A(x) {
  function B(y) {
    function C(z) {
      console.log(x + y + z);
A(1); // return 6 (1 + 2 + 3)

C can access y of B and X of A

  • B forms a closure containing A. B can access a's parameters and variables

  • C forms a closure containing B

  • B contains a, so C also contains a. C can access the parameters and variables of B and a. In other words, the scope of a and B is used

The opposite is not the case. A and B can't access a and B's variables, so we can't see one of C's and a's private variables.

name conflict

When two parameters or variables under the same closure scope have the same name, there will be a naming conflict

The closer scope has higher priority and the farthest scope has the lowest priority, which is the scope chain

The first element of the chain is the innermost scope, and the last element is the outermost scope

 function outside() {
  var x = 10;
  function inside(x) {
    return x;
  return inside;
result = outside()(20); // returns 20 instead of 10

The naming conflict occurs on return x, and the parameter X of inside conflicts with the external variable x

The scope is {inside, outside, global object}

Inside has the highest priority and returns the passed in 20 instead of the variable value 10 of the external function

Reading materials:

Review method: Practice (code write once, run once, test once), Google where you don't understand, read and take notes

Bottom line principle: you'd rather rewrite it once than copy and paste it

This review content has: the function part···

Review time: about 3 hours... I don't know why so long···

Typecho gets the last update time of the article Tue, 22 Mar 2016 03:47:00 +0800 Chakhsu Lau Before introducing the method, I will first talk about the PHP timestamp and the specific time conversion content, which is helpful to understand the method I used

Three built-in functions in PHP

 / / get the system time stamp 
 mktime (hour, minute, second, month, day, year) 
 / / convert the specified time into the time stamp 
 date (time format, time stamp) 
 / / convert the time stamp into a time convenient for reading

time -> date:

 $now = time(); 
 echo "timestamp is" $now; 
 echo "creation date is". Date ("Y / M / D H: I: s", $now);

The timestamp is 1458586366
It was created on March 22, 2016 at 2:52:46

mktime -> date:

 $d = mktime (2, 52, 46, 3, 22, 2016); 
 echo "timestamp is" $D; 
 echo "creation date is". Date ("Y / M / D H: I: s", $d);

It was created on March 22, 2016 at 2:52:46

Typecho get article time

Gets the time stamp of the publication of the article


Get the publication time of the article

 $this->date('F jS , Y \\a\t h:i a');

March 22nd , 2016 at 02:48 am

Gets the updated timestamp of the article


Gets the update time of the article

 echo date('F jS , Y \\a\t h:i a' , $this->modified);

March 22nd , 2016 at 02:51 am

It's almost like this. It took me a long time to figure it out.

Exception handling of JavaScript Tue, 22 Mar 2016 02:48:00 +0800 Chakhsu Lau exception handling

Throw an exception with the throw statement and catch it with the try... Catch statement

Exception type

JavaScript can throw any object. However, it is usually more efficient to create a target with one of the following exception types

  • ECMAScript exceptions

  • DOMException

  • nsIXPCException (XPConnect)

Throw statement

 throw expression;

The following code throws several different types of expressions

 throw "Error2";   // String type
throw 42;         // Number type
throw true;       // Boolean type
throw {toString: function() { return "I'm an object!"; } };

You can declare an object when you throw an exception. Then you can query the properties of the object in the capture block. The following example creates an object of type userexception, myuserexception, to be used in the throw statement.

 // Create an object type UserException
function UserException (message){
// Make the exception convert to a pretty string when used as
// a string (e.g. by the error console)
UserException.prototype.toString = function (){
  return + ': "' + this.message + '"'; 
// Create an instance of the object type and throw it
throw new UserException("Value too high");

Try... Catch statement

The following example uses the try... Catch statement, one of which is used to get the name of a month from an array based on the passed value. If the value of "unknown month" does not match the value of "month", an exception will be thrown if the value of "unknown month" is not matched

 function getMonthName(mo) {
  mo = mo - 1; // Adjust month number for array index (1 = Jan, 12 = Dec)
  var months = ["Jan","Feb","Mar","Apr","May","Jun","Jul",
  if (months[mo]) {
    return months[mo];
  } else {
    throw "InvalidMonthNo"; //throw keyword is used here
try { // statements to  try
  monthName = getMonthName(myMonth); // function could throw exception
catch (e) {
  monthName = "unknown";
  logMyErrors(e); // pass exception object to error handler -> your own function

Capture block

 catch (catchID) {

The identifier in the catch statement is used to capture the value of the block you throw

Jump to the capture block when an exception occurs

 try {
   throw "myException" // generates an exception
catch (e) {
// statements to handle any exceptions
   logMyErrors(e) // pass exception object to error handler

Terminal block

Use termination blocks to make your script exit gracefully when an exception occurs

try {
    writeMyFile(theData); //This may throw a error
    handleError(e); // If we got a error we handle it
}finally {
    closeMyFile(); // always close the resource

If the end block returns a value, it will be the return value of the entire try catch finally process

 function f() {
  try {
    throw "bogus";
  } catch(e) {
    return true; // this return statement is suspended
                 // until finally block has completed
    console.log(2); // not reachable
  } finally {
    return false;  // overwrites the previous "return"
    console.log(4); // not reachable
  // "return false" is executed now  
  console.log(5); // not reachable
f(); // console 0, 1, 3; returns false

Error matching object

'name' provides a regular error class (e.g., 'domexception' or 'error')

'message 'usually provides a concise message to convert from the error object to a string

 function doSomethingErrorProne () {
  if (ourCodeMakesAMistake()) {
    throw (new Error('The message'));
  } else {
try {
catch (e) {
  console.log(; // logs 'Error'
  console.log(e.message); // logs 'The message' or a JavaScript error message)

Reading materials:

Review method: Practice (code write once, run once, test once), Google where you don't understand, read and take notes

Bottom line principle: you'd rather rewrite it once than copy and paste it

The content of this review includes: exception handling

Review time: about 2 hours... I don't know why so long···

Flow control and iteration statement of JavaScript Mon, 21 Mar 2016 12:49:00 +0800 Chakhsu Lau Statement block
   statement_ 1;   statement_ 2;
   statement_ 3;
   statement_ n;

here { ...; } It's a statement block.

 Var x = 1; 
 {var x = 2; 
 alert (x); / / the output result is 2

var The defined variables are declared local and global
let The defined variable is block scoped

Conditional statement


A kind of conditional judgment

 if (condition) {
  statement_ 1;
[else {
  statement_ 2. }] / / it is recommended to use strict statement block mode, and else is optional

Multiple conditional judgment

 if (condition_ 1) {
  statement_ 1;
[else if (condition_ 2) {
  statement_ 2;
[else if (condition_ n_ 1) {
  statement_ n_ 1;
[else {
  statement_ n;

These values will be calculated below false

  • false

  • undefined

  • null

  • zero

  • NaN

  • Empty string (')


 function checkData() {
  if (document.form1.threeChar.value.length == 3) {
    return true;
  } else {
    alert("Enter exactly three characters. " +
      document.form1.threeChar.value + " is not valid.");
    return false;

Switch statement

 switch (expression) {
   case label_ 1:
      statements_ 1
   case label_ 2:
      statements_ 2
      statements_ def

Find a case statement that matches the expression. If found, jump to the clause, execute the related statement, and then jump out of switch


 switch (fruittype) {
   case "Oranges":
      document.write("Oranges are $0.59 a pound.<br>");
   case "Apples":
      document.write("Apples are $0.32 a pound.<br>");
   case "Bananas":
      document.write("Bananas are $0.48 a pound.<br>");
   case "Cherries":
      document.write("Cherries are $3.00 a pound.<br>");
   case "Mangoes":
   case "Papayas":
      document.write("Mangoes and papayas are $2.79 a pound.<br>");
      document.write("Sorry, we are out of " + fruittype + ".<br>");
document.write("Is there anything else you'd like?<br>");

Loop statement

Loop flow control statements include:

  • for Statement

  • do...while Statement

  • while Statement

  • label Statement

  • break Statement

  • continue Statement

For statement

 for ([initialExpression]; [condition]; [incrementExpression])
  • [initialexpression]: initializes the expression and executes if it exists. This expression usually initializes one or more loop counters, and syntax allows you to set an expression of arbitrary complexity. Variables can also be declared in expressions

  • [condition]: condition expression. If the value of the expression is true, the loop statement is executed; if it is flash, the loop is terminated. To completely ignore this conditional expression, set the value of the expression to true

  • Statement: statement to be executed. If you want to execute more than one statement, enclose the statement in brackets ({...})

  • [incrementexpression]: cumulative expression. If it exists, execute, and then return to step 2 to execute the statement


 <script type="text/javascript">
function howMany(selectObject) {
   var numberSelected = 0;
   for (var i = 0; i < selectObject.options.length; i++) {
      if (selectObject.options[i].selected)
   return numberSelected;
<form name="selectForm">
      <strong>Choose some music types,  then click the button below:</strong>
      <select name="musicTypes" multiple="multiple">
         <option selected="selected">R&B</option>
         <option>New Age</option>
       <input type="button" value="How many are selected?"
         onclick="alert ('Number of options selected: ' + howMany(document.selectForm.musicTypes))"/>

Do... While statement

while (condition);

The statement is executed once before the conditional judgment

While statement

 while (condition)


 n = 0;
x = 0;
while (n < 3) {
   x += n;

Using the while statement requires that you avoid loops, which means that the conditions in the loop eventually become false

Label statement

The label provides an identifier that you can refer to elsewhere in your program

 label :

For example, the marker markloop identifies a while loop

while (theMark == true) {

Break statement

Use the break statement to terminate the loop switch or link to the label statement

break label;

Common examples

 for (i = 0; i < a.length; i++) {
   if (a[i] == theValue)

Example of interrupt jump to label statement

 var x = 0;
var z = 0
labelCancelLoops: while (true) {
    console.log("Outer loops: " + x);
    x += 1;
    z = 1;
    while (true) {
        console.log("Inner loops: " + z);
        z += 1;
        if (z === 10 && x === 10) {
            break labelCancelLoops;
        } else if (z === 10) {

Continuous statement

Use the continue statement to restart a while, do while, for, or label statement

continue label;

Common examples

 var i = 0;
var n = 0;
while (i < 5) {
  if (i == 3) {
  n += i;

Examples of continuous to label statements

  while (i < 4) {
    i += 1;
      while (j > 4) {
        j -= 1;
        if ((j % 2) == 0) {
          continue checkj;
        console.log(j + " is odd.");
      console.log("i = " + i);
      console.log("j = " + j);

Object operation statement

For... In statement

For... In statement loops through a specified variable to loop all enumerable properties of an object

 for (variable in object) {

The name of the object and the values of the last property of the loop are listed

 function dump_ props(obj, obj_ name) {
   var result = "";
   for (var i in obj) {
      result += obj_ name + "." + i + " = " + obj[i] + "<br>";
   result += "<hr>";
   return result;

For each... In statement

Similar to for... In, but let the values of object properties be retrieved recursively instead of acting on their names

 var sum = 0;
var obj = {prop1: 5, prop2: 13, prop3: 8};
for each (var item in obj) {
  sum += item;
print(sum); // prints "26", which is 5+13+8

For... Of statement

The for... Of statement creates a loop (including array, map, set, arguments, etc.) on an iteratable object to call a custom statement linked iteration to be executed for each unique property of the value

 for (variable of object) {

The result of the for... In loop traversal is the subscript of the array element, while the result of the for... Of traversal is the value of the element

 Let arr = [3, 5, 7]; = hello "; 
 for (let I in ARR) {console. Log (I); / / logs" 0 "," 1 "," 2 "," foo "
} for (let I of ARR) {console. Log (I); / / logs" 3 "," 5 "," 7 "/ / note that there is no Hello}

Reading materials:

Review method: Practice (code write once, run once, test once), Google where you don't understand, read and take notes

Bottom line principle: you'd rather rewrite it once than copy and paste it

The content of this review is: process control, iterative statements

Review time: about 3 hours... I don't know why so long···

Enable http / 2 support Sun, 20 Mar 2016 23:51:00 +0800 Chakhsu Lau Optimization for HTTP / 1. X
  1. Http / 2 multiplexes a TCP connection for multiple transmissions, that is, asynchronous connection multiplexing

  2. Http / 2 merges resource files appropriately, which is header compression

  3. Push requests to the server in a certain order of bandwidth, that is, push requests to the server in a certain order

  4. Fully semantic compatible with HTTP 1.1···

Conditions for enabling http / 2

  • Based on TLS deployment, that is to say, you need to configure HTTPS first, because both chrome and Firefox support only http / 2 over TLS

  • The HTTP server needs to be supported, that is, it needs to upgrade to a newer version. For example, nginx needs to be upgraded to 1.9.7 or above

Http / 2 support

Currently, browsers that support HTTP / 2 include chrome 41 +, Firefox 36 +, Safari 9 +, ie 11 and edge on Windows 10

Configure http / 2

Http / 2 needs to be configured before http / 2 is enabled. Here is a brief recapitulation of what needs to be done

First, upgrade OpenSSL

Second, upgrade nginx and OpenSSL to compile together, and also to --with-http_ v2_ module --with-http_ ssl_ module The two modules are compiled together

Then, configure the configuration file of nginx's site

 server {
    listen 443 ssl http2 default_ server;

    ssl_ certificate    server.crt;
    ssl_ certificate_ key server.key;

Finally, restart and check whether it is turned on correctly···

Some configuration tutorials

Here's a list of the articles I've written to help you configure,

Certificate issuing and configuration of let's encrypt

Issuing certificate request file CSR with ECC algorithm

Concatenate certificate chain and configure nginx to enable SSL

SSL configuration optimization of nginx

Enable HSTs and apply for HSTs preload list

Chacha20-poly1305 cipher suite of OpenSSL

Chacha20-poly1305 encryption suite on nginx

What I know about HSTs

Enable certificate transparency policy

Some small OCSP practices