LiNPX https://www.linpx.com/ zh-CN LiNPX is a personal blog. Of course, the content in it mainly focuses on programmers and the Internet. Most of the content is personal learning and memos. Of course, there are some other tutorials and some insights. I hope that while I grow up, I can also help you Sun, 24 Apr 2016 15:46:00 +0800 Sun, 24 Apr 2016 15:46:00 +0800 Some Typecho plug-ins I am currently using https://www.linpx.com/p/currently-im-using-some-of-the-typecho-plugin.html https://www.linpx.com/p/currently-im-using-some-of-the-typecho-plugin.html Sun, 24 Apr 2016 15:46:00 +0800 Chakhsu Lau This is a suggestion for using some plug-ins in my theme

to update

August 27, 2016:
Change CommentFilter to SmartSpam
http://www.yovisun.com/archive/typecho-plugin-smartspam.html

Plug in in use

TYPECHO Automatic Translation SLUG Plug in
http://blog.tapasy.com/baiduslug.html

CommentToMail comment email reminder plug-in
http://www.byends.com/typecho/CommentToMail-v2-0-0.html

Google Sitemap Builder
http://www.imhan.com/typecho/

Typecho Cache Plug in
https://blog.phpgao.com/tpcache_for_typecho.html

Some introductions

In use Lpisme At the same time, there is no conflict in the use of these plug-ins, and they can be used together with the theme with confidence. In addition, the code design of the theme is lightweight, no JQ, no front-end framework, fast loading, and can be faster with cdn. Moreover, the use of these plug-ins will not affect the loading of web pages as some of WP's plug-ins do.

The theme uses two small JS libraries, especially the prismjs code highlighting this, which can be modified according to your own needs. The modification method is the same as that of the official website documents. The other is the instantclickjs, which is used to speed up the page loading. If you test for conflicts, you can close it in the background appearance settings.

For comment garbage filtering, it is recommended to close the background and replace this function with plug-ins.

other

If you have a better plug-in that you are using, I hope you can leave a recommendation in the comments^^

]]>
thirty-seven https://www.linpx.com/p/currently-im-using-some-of-the-typecho-plugin.html#comments https://www.linpx.com/feed/
Learning Notes of UML Class Diagram https://www.linpx.com/p/uml-class-diagram-of-the-study-notes.html https://www.linpx.com/p/uml-class-diagram-of-the-study-notes.html Fri, 22 Apr 2016 06:41:00 +0800 Chakhsu Lau Class Diagram is used to describe the classes contained in the system and their relationships, and help people simplify their understanding of the system. It is an important product of the system analysis and design phase, and also an important model basis for system coding and testing.

class

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

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

Class Diagram uses different classes that appear in the system to describe the static structure of the system. It is used to describe different classes and their relationships.

In the system analysis and design phase, classes can generally be divided into three types, namely, Entity Class, Control Class and Boundary Class. The following is a brief description of these three types:

(1) Entity class: The entity class corresponds to each entity in the system requirements. They usually need to be saved in the permanent storage, and are generally recorded using database tables or files. Entity classes include both classes that store and transfer data, and classes that operate data. Entity classes are derived from nouns in the requirement description, such as students, commodities, etc.

(2) Control class: the control class is used to reflect the execution logic of the application, provide corresponding business operations, and abstract the control class to reduce the coupling between the interface and the database. The control class is generally a noun converted from a verb object phrase (verb+noun). For example, adding a commodity corresponds to a commodity 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 boxes, windows, menus, etc.

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

Class relationship

  • Generalization
  • Realize
  • Aggregation
  • Composition
  • Association
  • Dependency

Generalized relation

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

The inheritance relationship is is-a; If two objects can be represented by is-a, it is an inheritance relationship: (.. Is..)

Eg: Bicycles are cars, cats are animals

The generalization relation is directly represented by a hollow arrow; As shown in the figure below (A inherits from B);

 1gen.png

Note: In the final code, the generalization relationship is shown as inheriting non abstract classes

Realizing relationships

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

Eg: "Car" is an abstract concept, which cannot be directly used to define objects in reality; Only specific subclasses (cars or bicycles) can be used to define objects ("cars" are represented by abstract classes in C++, and interfaces are easier to understand in Java)

 1rea.png

Note: In the final code, the implementation relationship is represented as an inheritance abstract class

Aggregation relation

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

 1agg.png

Aggregation relationship is used to represent the relationship between entity objects, and to represent the semantics that the whole is composed of parts; For example, a department consists 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 filled diamond arrow, as shown in the figure below, indicating that A constitutes B, or B is composed of A;

 1com.png

Like the aggregation relationship, the combination relationship also represents the semantics of the whole composed of parts; For example, the company consists of multiple departments;

However, the combination relationship is a special aggregation relationship with strong dependency. If the whole does not exist, then the part does not exist; For example, if the company does not exist, the department will not exist;

Association

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

For example, there is an association between passengers and tickets; Students and schools are related;

The association relationship does not emphasize direction by default, which means that objects know each other; If the direction is especially emphasized, as shown in the figure below, it means that A knows B, but B does not know A;

 1ass.png

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

Dependencies

Dependencies are represented by a set of dotted lines with arrows; As shown in the figure below, A depends on B; He describes the relationship between an object and another object during operation;

 1dep.png

Different from the association relationship, it is a temporary relationship, usually generated during the run time, and changes with the run time; Dependencies may also change;

Obviously, dependency also has a direction. Bidirectional dependency is a very bad structure. We should always maintain one-way dependency and eliminate the occurrence of two-way dependency;

Note: In the final code, the dependency relationship is reflected in the class construction method and the incoming parameters of the class method, and the arrow points to the call relationship; Dependency processing temporarily knows whether to "use" the methods and attributes of the other party or not;

reference resources

design-patterns.readthedocs.org/zh_CN/latest/read_uml.html

www.ibm.com/developerworks/cn/rational/r-uml/

]]>
two https://www.linpx.com/p/uml-class-diagram-of-the-study-notes.html#comments https://www.linpx.com/feed/
Learning notes of sequence diagram https://www.linpx.com/p/timing-diagram-learning-notes.html https://www.linpx.com/p/timing-diagram-learning-notes.html Fri, 22 Apr 2016 06:08:00 +0800 Chakhsu Lau Sequence Diagram, also called sequence diagram or sequential diagram, is a UML behavior diagram. It displays dynamic collaboration among multiple objects by describing the time sequence of sending messages between objects. It can represent the sequence of use case behavior. When a use case behavior is executed, each message in the sequence diagram corresponds to a class operation or trigger event in the state machine that causes the transition. via: wiki

brief introduction

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

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

Time sequence diagram representation: the objects participating in the interaction are arranged horizontally at the top of the time sequence diagram, and a vertical dotted line is drawn at the bottom of each object. Object A sends messages to object B, which 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 arrows are placed horizontally, and the closer they are to the top, the earlier they are sent

Sequence diagram track: the sequence diagram provides a clear visual track over time

Sequence Diagram Elements

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

object

Object: The object in the sequence diagram plays a role in the interaction

Object symbol: objects in the sequence diagram are represented in the same way as objects in the object diagram. The object name is contained in a rectangle and underlined

Object creation timing: objects can be created at the beginning of interaction or during interaction

  • At the top: if the object is at the top of the sequence diagram, it means that the object already exists at the beginning of the interaction
  • Not on top: if the object's position is not on top, the object is created during interaction

lifeline

Lifeline: A lifeline is a vertical dotted line, which indicates the existence of objects. In the sequence diagram, there is a lifeline at the bottom of each object

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

Lifeline of objects: objects and lifelines together are the lifelines of objects. This concept includes object icons and lifeline icons below objects

activation

Activation: represents the period when an object in the sequence diagram executes 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: refers to that the object is idle and waiting for a message to activate it

Activation representation: when the object is in the activation period, the lifeline can be widened to a rectangle, and this rectangular bar becomes the activation bar

Time for activation and deactivation:

  • Activate: Object activation is activated at the top of the activation bar
  • Deactivation: Deactivation at the bottom of the activation bar usually occurs when a message leaves the object lifeline

news

Message concept: defines the class of information exchange in interaction and collaboration, and models the communication content between objects

Message action:

  • Action type: messages allow to transfer information (transfer parameters) between entities, allow entities to request other services, and communicate between objects by sending and receiving messages;
  • Results: messages can trigger operations, raise signals, or make target objects 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 an asynchronous communication between explicitly named objects
  • Synchronous communication: directly call the method of the object and execute the method to return the result. This operation with return control mechanism is synchronous communication

Difference between messages in sequence diagram and collaboration diagram: messages in sequence diagram emphasize order, and messages in collaboration diagram emphasize relationship between objects exchanging messages

reference resources

www.ibm.com/developerworks/cn/rational/rationaledge/content/feb05/bell/3101.html

blog.csdn.net/shulianghan/article/details/17927131

design-patterns.readthedocs.org/zh_CN/latest/read_uml.html

]]>
zero https://www.linpx.com/p/timing-diagram-learning-notes.html#comments https://www.linpx.com/feed/
JavaScript operators https://www.linpx.com/p/jaxvascxript-operator.html https://www.linpx.com/p/jaxvascxript-operator.html 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 its right operand to its left operand

name shorthand Equivalent to
assignment Assignment x = y , x = y
Addition 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
Complementary assignment Remainder assignment x %= y , x = x % y
Exponentiation 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
Unsigned 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

Deconstructing assignment The designing assignment syntax is a Javascript expression that can extract data from the array structure or object literal corresponding to an array or object

 var foo = ["one", "two", "three"]; //Do not use deconstruction var one   = foo[0]; var two   = foo[1]; var three = foo[2]; //Use Deconstruction var [one,  two, three] = foo;

Comparison operator

A comparison operator compares its operands and returns the logical value of whether an 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 Example of returning true
Equal (==) Returns true if the operands on both sides are equal 3 == var1 , "3" == var1 , 3 == '3'
Not equal (!=) Returns true if the operands on both sides are not equal var1 != 4 , var2 != "3"
Full Strict equal (===) Returns true when the operands on both sides are equal and the type is the same 3 === var1
Incomplete Strict not equal (!==) Returns true when the operands on both sides are not equal or the types are different var1 !== "3" , 3 !== '3'
Greater than (>) If the left operand is greater than the right operand, return true var2 > var1 , "12" > 2
Greater than or equal (>=) The left operand is greater than or equal to the right operand and returns true var2 >= var1 , var1 >= 3
Less than (<) If the left operand is less than the right operand, return true var1 < var2 , "2" < 12
Less than or equal (<=) The left operand is less than or equal to the right operand and returns true var1 <= var2 , var2 <= 5

Arithmetic operator

Arithmetic operators use numeric values (literal quantities or variables) as operands and return 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 Example
%(Remaining) Binary operator Returns the remainder after division 13% 5 returns 3
++(self increasing) Unary operator Adds one to the value of the operand var x=3; console.log(++x); console.log(x); var y=3; console.log(y++); console.log(y); // four thousand four hundred and thirty-four
--(self subtracting) Unary operator Subtracts the value of the operand by one var x=3; console.log(--x); var y=3; console.log(y--);
-(unary negative sign) The unary operator returns the negative value of the operand var x=3; console.log(-x);// Input-3
+(unary positive sign) The unary operator returns the positive value of the operand console.log( +'3' ); console.log( '3' ); console.log(+true); // 3 '3' 1

Bitwise Operators

Bit operators treat their operands as 32-bit binary strings (consisting of 0 and 1) rather than decimal octal or hexadecimal numbers

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

Bitwise logical operator

expression result Binary Description
15 \& 9 nine 1111 \& 1001 = 1001
15 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 takes two operands:

  • Number to be shifted
  • A number that specifies how many bits to move the first number

The direction of the shift is controlled by the operator

operator describe
<<(left shift) Moves the first operand to the left by the specified number of bits Left out position is abandoned The bits shifted from the left are discarded. The extra bits on the right are filled by 0
>>(Move right with sign) Moves the first operand to the right by the specified number of bits The right out position is abandoned The extra space on the left is filled by the leftmost number of the original value
>>>(Shift zero filling to the right) Moves the first operand to the right by the specified number of bits The right out position is abandoned The extra space on the left 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 && Example of the (logical AND) operator

 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 || Example of the (logical OR) operator

 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 Example of the (logical NOT) operator

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

String operator

(+) connected in series

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

(+=) connected 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 a value to status, otherwise it will "minor" Assign value to status

comma operator

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

It is often used in the for loop 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

The unary operator only corresponds to one operand

Delete operator

The delete operator deletes an object or an object's property or an element at a specified index in an array

 delete objectName; delete objectName.property; 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 it is unsuccessful, 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

If the specified property is in the specified object, true will be returned

 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: https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Guide

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

Bottom line principle: prefer rewriting once rather than copying and pasting

This review includes: operators···

Review time: it lasted for several days intermittently... I was drunk too···

]]>
four https://www.linpx.com/p/jaxvascxript-operator.html#comments https://www.linpx.com/feed/
JavaScript closures and arrow functions https://www.linpx.com/p/jaxvascxript-function-two.html https://www.linpx.com/p/jaxvascxript-function-two.html 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 accessible by external functions

External functions cannot access variables and functions defined in internal functions

When the life cycle of an internal function is greater than that of an external function, the life cycle of variables and functions defined in the external function will be greater than that of the external function itself because the internal function can access the scope of the external function

When an internal function is accessed by any external function scope in a certain way, a closure And then there is

 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"

The following example returns an object containing internal variable methods that can operate on external functions

 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.setName("Oliver"); pet.setSex("male"); pet.getSex();                   //  male pet.getName();                  //  Oliver

The embedded variables of an embedded function are like the safe of an embedded function. They will keep "stable" -- and safe -- data for embedded functions to run. These embedded functions are not even assigned to a variable, or do not 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 an external function, the variable can no longer be pointed to 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 the closure is very weird.
You must be very careful when using it, because what this refers to completely depends on where the function is called, not where it is defined.

Use arguments object

The actual parameters of the function will be saved in an array like arguments object. In the function, you can find the arguments passed in as follows:

 arguments[i]
  • 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 to concatenate strings. The only predetermined parameter is the character used to separate the connecting parts in the connected string. This function is defined as follows:

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

You can pass any number of parameters to this function, which will connect each parameter 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

  • The arguments variable is only an "array like object", not an array
  • Calling it an array like object means that it has an index number and a Length attribute
  • 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 function parameters is undefined

 function multiply(a,  b) { b = typeof b !== 'undefined' ?  b : 1; return a*b; } multiply(5); //  five

When calling the function, no actual parameter is passed to b, then its value is undefined, so the calculation of a * b results in NaN returned by the function

Remaining parameters

Remaining parameter syntax allows an indefinite number of parameters to be represented as arrays

 function multiply(multiplier, ... theArgs) { return theArgs.map(x => multiplier * x); } var arr = multiply(2, 1, 2, 3); console.log(arr); //  [2, 4, 6]

Arrow function

Arrow function expression (also called fat arrow function, Fat arrow function) has a shorter syntax than the function expression and lexical binding of this value. Arrow functions are always anonymous.

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

  • More concise functions
  • this

More concise functions

 var a = [ "Hydrogen", "Helium", "Lithium", "Beryl­lium" ]; var a2 = a.map(function(s){ return s.length }); var a3 = a.map( s => s.length );

this

Before the arrow function appeared, each new function redefined its own value of this (in strict mode, a new object is undefined in the constructor, and functions called through context objects are called "object methods", 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. this.age++; }, 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. self.age++; }, 1000); }

In addition, creating a bound function can make this value be correctly passed to the growUp() function

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

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

Reading materials: https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Guide

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

Bottom line principle: prefer rewriting once rather than copying and pasting

This review includes: the second part of the function···

Review time: it lasted for several days intermittently... I was drunk too···

]]>
four https://www.linpx.com/p/jaxvascxript-function-two.html#comments https://www.linpx.com/feed/
Functions of JavaScript https://www.linpx.com/p/function-of-jaxvascxript-1.html https://www.linpx.com/p/function-of-jaxvascxript-1.html Sun, 27 Mar 2016 01:04:00 +0800 Chakhsu Lau Defining Functions

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

  • The name of the function
  • A list of function arguments enclosed in parentheses () and enclosed by commas , division
  • Function functions, enclosed in curly braces {}, are some JavaScript statements used to define function functions

for example

 function square(number) { return number * number; }

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

If you pass an object as a parameter and the function changes the properties of the object, such changes are visible outside the function

 function myFunc(theObject) { theObject.make = "Toyota"; } var mycar = {make: "Honda",  model: "Accord",  year: 1998}, var x, y; X=mycar.make;//The value obtained by x is "Honda" myFunc(mycar); Y=mycar.make;//The value obtained by y is "Toyota" //(The value of the make attribute is changed in the function)

Function expression

 var square = function(number) { return number * number }; var x = square(4); //  X yields a value of 16

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

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

The function expression is very convenient when passing the function as an argument to other functions

The following example demonstrates how to define a function called map, and then call an anonymous function as its first parameter

 function map(f, a) { Var result=[],//Create a new array i; 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 according to 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

The calling function will actually execute these actions with the given parameters

For example, if you define the function square, you can call it as follows

 square(5);

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

 console.log(square(5)); /* ... */ function square(n) { return n*n }

The function field refers to the place where the function is declared, or the whole program when the function is declared at the top level

The meaning can only use 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; }

Functions can be recursive; That is, the function can call itself. The following example is to calculate the recursive factorial value

 function factorial(n){ if ((n == 0) || (n == 1)) return 1; else return (n * factorial(n - 1)); } var a, b, c, d, e; a = factorial(1); //  1 Assign value to a b = factorial(2); //  2 Assign a value to b c = factorial(3); //  6 Assign a value to c d = factorial(4); //  24 Assign value to d e = factorial(5); //  120 assigned to e

Scope of function

A function can obtain any variable and sub function defined in its domain

  • Functions defined in the global domain can obtain all variables defined in the global domain
  • A child function defined in a function can obtain any variable defined in its parent function or obtained by its parent function
 //The following variables are defined in the global scope domain var num1 = 20, num2 = 3, name = "Chamahk"; //This function is defined in the global scope function multiply() { return num1 * num2; } multiply(); //  Returns 60 //Examples of nested functions function getScore () { var num1 = 2, num2 = 3; function add() { return name + " scored " + (num1 + num2); } return add(); } getScore(); //  Returns "Chamahk scored 5"

Scope and function stack

recursion

Functions can point to and call themselves (call itself) in three ways:

  1. By using the function's name
  2. Use arguments. callee (ECMAScript (ES5) forces use of arguments. callee() in strict mode)
  3. Use a variable name under the scope to point to the function (an in scope variable references to the function)

Function definition:

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

In this function body, the following statements are equivalent

  • bar()
  • arguments.callee()
  • foo()

Calling its own function is called recursive function

In a sense, recursion is close to a loop
Both execute the same code repeatedly, and both need a termination condition to avoid infinite loops or infinite recursion

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

Convert to a recursive function and call it

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

Some algorithms cannot be implemented simply by loops. For example, when obtaining all nodes in the tree structure, it is much easier to implement recursively

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

Compared with the loop function, each recursive call here generates more recursion

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

 function foo(i) { if (i < 0) return; console.log('begin:' + i); foo(i - 1); console.log('end:' + i); } foo(3); // Output: // begin:3 // begin:2 // begin:1 // begin:0 // end:0 // end:1 // end:2 // end:3

Nested functions and closures

Nest another function inside a function
Nested functions are private members of container functions. It also forms a closure
A closure is an expression (usually a function) that can have its own environment and variables

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
  • The internal function forms a closure: it can access the parameters and variables of the external function, but the external function cannot use its parameters and variables

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

Internal functions form closures. You can call external functions and specify the parameters of external and internal 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 Variable

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

Multilayer Nested Functions

Functions can be nested multiple levels

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, C can access B and A

Closures can contain multiple scopes, which recursively contain all the function scopes containing them. This is called scope chaining

 function A(x) { function B(y) { function C(z) { console.log(x + y + z); } C(3); } B(2); } 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, C links the scopes of B and A in this order

The opposite is not true. A cannot access C because A cannot see the parameters and variables in B, C is a variable in B, so C is private to B.

name conflict

When two parameters or variables under the same closure scope have the same name, naming conflicts will occur

The closer scope has higher priority, and the farthest scope has the lowest priority. This 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 occurred on return x, The inside parameter x conflicts with the external variable x

The scope is {inside, outside, Global Object}

The inside has the highest priority and returns the passed 20 instead of the variable value 10 of the external function


Reading materials: https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Guide

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

Bottom line principle: prefer rewriting once rather than copying and pasting

This review includes: part of function···

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

]]>
zero https://www.linpx.com/p/function-of-jaxvascxript-1.html#comments https://www.linpx.com/feed/
Typecho gets the last update time of the article https://www.linpx.com/p/typecho-get-the-last-update-time.html https://www.linpx.com/p/typecho-get-the-last-update-time.html Tue, 22 Mar 2016 03:47:00 +0800 Chakhsu Lau Before introducing the method, let's talk about the content of PHP timestamp and specific time conversion, which is helpful to understand the method I use

Three built-in functions in php

 time() //Get system timestamp mktime(hour, minute,second,month,day,year) //Converts the specified time to a timestamp Date (time format, timestamp) //Convert timestamps into easy to read time

time -> date:

 $now = time(); Echo "The timestamp is". $now; Echo "The creation date is". date ("Y/m/d h: i: s", $now);

Output:
Time stamp is 1458586366
Created on March 22, 2016 2:52:46

mktime -> date:

 $d=mktime(2, 52, 46, 3, 22, 2016); Echo "The timestamp is". $d; Echo "The creation date is". date ("Y/m/d h: i: s", $d);

Output:
Time stamp is 1458586366
Created on March 22, 2016 2:52:46

Typecho Get Article Time

Get the time stamp of the article's publication

 $this->created();

Get the publishing time of the article

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

Output:
March 22nd , 2016 at 02:48 am

Get the updated timestamp of the article

 $this->modified();

Get the update time of the article

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

Output:
March 22nd , 2016 at 02:51 am

That's about it. It took a long time to figure it out.

]]>
four https://www.linpx.com/p/typecho-get-the-last-update-time.html#comments https://www.linpx.com/feed/
Exception handling of JavaScript https://www.linpx.com/p/jaxvascxript-exception-handling.html https://www.linpx.com/p/jaxvascxript-exception-handling.html Tue, 22 Mar 2016 02:48:00 +0800 Chakhsu Lau exception handling

Throw an exception with the throw statement and try The catch statement captures and processes it

Exception type

JavaScript can throw arbitrary objects. However, it is usually more efficient to use one of the following exception types to create targets

  • 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 an exception is thrown. Then you can query the object's attributes in the snap block. The following example creates a UserException type object myUserException to be used in the throw statement.

 // Create an object type UserException function UserException (message){ this.message=message; this.name="UserException"; } // 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.name + ': "' + 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 try Catch statement, in which a function is used to obtain the name of a month from an array according to the passed value. If the value does not match the month value, an exception with an "InvalidMonthNo" value will be thrown, and then set the monthName variable to unknown in the capture block statement

 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", "Aug","Sep","Oct","Nov","Dec"]; 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 }

Snap Block

 catch (catchID) { statements }

The capture block specifies an identifier (catchID in the above statement) to store the value specified by the throw statement; You can use this identifier to get the exception information thrown

Jump to snap block when exception occurs

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

End block

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

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

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

 function f() { try { console.log(0); throw "bogus"; } catch(e) { console.log(1); return true; // this return statement is suspended // until finally block has completed console.log(2); //  not reachable } finally { console.log(3); 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 general error classes (e.g., 'DOMException' or 'Error')

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

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

Reading materials: https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Guide

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

Bottom line principle: prefer rewriting once rather than copying and pasting

This review includes: exception handling

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

]]>
zero https://www.linpx.com/p/jaxvascxript-exception-handling.html#comments https://www.linpx.com/feed/
JavaScript process control and iteration statements https://www.linpx.com/p/jaxvascxript-flow-control-and-iterative-statement.html https://www.linpx.com/p/jaxvascxript-flow-control-and-iterative-statement.html Mon, 21 Mar 2016 12:49:00 +0800 Chakhsu Lau Statement block
 { statement_1;   statement_2; statement_3; ... statement_n; }

here { ...; } It is the statement block.

 var x = 1; { var x = 2; } alert(x); //  The output result is 2

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

Conditional judgement statement

if...else

A kind of conditional judgment

 if (condition) { statement_1; } [else { statement_2; }]//Strict statement block mode is recommended, and statement else is optional

Multiple condition judgment

 if (condition_1) { statement_1; } [else if (condition_2) { statement_2; }] ... [else if (condition_n_1) { statement_n_1; }] [else { statement_n; }]

The following values will be calculated false

  • false
  • undefined
  • null
  • zero
  • NaN
  • Empty string ("")

example

 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 [break;] case label_2: statements_2 [break;] ... default: statements_def [break;] }

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

example

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

Loop statement

Circular flow control statements include:

  • for Statement
  • do...while Statement
  • while Statement
  • label Statement
  • break Statement
  • continue Statement

For statement

 for ([initialExpression];  [condition];  [incrementExpression]) statement
  • [initialExpression]: Initialize the expression. If it exists, execute it. This expression usually initializes one or more circulating counters, and syntax allows you to set an expression of any complexity. Variables can also be declared in expressions
  • [condition]: Condition expression. If the value of the expression is true, the circular statement will be executed; If it is flat, the loop terminates. To completely ignore this conditional expression, set the value of this expression to true
  • Statement: the statement to be executed. If you want to execute multiple statements, enclose them with brackets ({...})
  • [incrementExpression]: cumulative expression. If it exists, execute it, and then go back to step 2 to execute the statement

example

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

Do... while statement

 do statement while (condition);

Statement will be executed once before condition judgment

While statement

 while (condition) statement

example

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

When using the while statement, you need to ensure that an endless loop is avoided, that is, the conditions in the loop will eventually become false

Label statement

Label provides an identifier that allows you to refer to other locations in your program

 label : statement

For example, the markLoop tag identifies a while loop

 markLoop: while (theMark == true) { doSomething(); }

Break statement

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

 break; break label;

Common examples

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

Example of Interrupt Jumping 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) { break; } } }

Consecutive statement

The continue statement can be used to restart a while, do-while, for, Or label statement

 continue; continue label;

Common examples

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

Example of continuous to label statements

 checkiandj: while (i < 4) { console.log(i); i += 1; checkj: while (j > 4) { console.log(j); 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 Loop through a specified variable to loop through all enumerable properties of an object

 for (variable in object) { statements }

For example, the following function passes two parameters: an object and the name of the object, then loops over the object's properties, and finally gets a string listing all the property names and values of the object

 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

And for In is similar, but the values of object attributes are 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, Parameter objects (arguments, etc.), call a custom iteration linked to the statement to be executed for each unique attribute of the value

 for (variable of object) { statement }

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

 let arr = [3, 5, 7]; arr.foo = "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: https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Guide

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

Bottom line principle: prefer rewriting once rather than copying and pasting

The review content includes: process control, iteration statement

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

]]>
zero https://www.linpx.com/p/jaxvascxript-flow-control-and-iterative-statement.html#comments https://www.linpx.com/feed/
Enable HTTP/2 support https://www.linpx.com/p/enable-http2-support.html https://www.linpx.com/p/enable-http2-support.html 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 will appropriately merge resource files, that is, header compression
  3. HTTP/2's Server Push feature allows the server to make full use of bandwidth and push resources to the client in a certain priority order, that is, request feedback pipelining
  4. Fully semantic compatible with HTTP 1.1···

Conditions for enabling HTTP/2

  • TLS based deployment means that HTTPS needs to be configured first, because Chrome and Firefox both support only HTTP/2 Over TLS
  • The HTTP server needs to support, 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

HTTPS needs to be configured before HTTP/2 is enabled. Here we will simply repeat what needs to be done

First, upgrade OpenSSL

Secondly, upgrade Nginx and compile it together with OpenSSL --with-http_v2_module --with-http_ssl_module Compile two modules 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 correctly started···

Some configuration tutorials

Here are the help configurations of the articles written previously,

Let's Encrypt certificate issuance and configuration
https://www.linpx.com/p/lets-encrypt-certificate-and-configuration.html

Issue certificate request file CSR with ECC algorithm
https://www.linpx.com/p/ecc-algorithm-is-used-to-issue-the-certificate-request-file-csr.html

Cascade the certificate chain and configure Nginx to enable SSL
https://www.linpx.com/p/the-series-of-certificate-chain-and-configure-nginx-to-open-ssl.html

Optimization of Nginx's SSL configuration
https://www.linpx.com/p/ssl-configuration-optimization.html

Enable HSTS and apply for HSTS Preload List
https://www.linpx.com/p/hsts-and-hsts-preload-list-enabled-applications.html

ChaCha20-Poly1305 cipher suite for OpenSSL
https://www.linpx.com/p/the-openssl-chacha20poly1305-cipher-suite.html

Install ChaCha20-Poly1305 encryption suite to Nginx
https://www.linpx.com/p/nginx-chacha20poly1305-encryption-suite.html

My little knowledge of HSTS
https://www.linpx.com/p/i-know-little-about-hsts.html

Enable Certificate Transparency policy
https://www.linpx.com/p/https-certificate-to-enable-transparency-certificate-policy.html

Some practices of OCSP Staging
https://www.linpx.com/p/some-small-practice-of-stapling-ocsp.html

]]>
five https://www.linpx.com/p/enable-http2-support.html#comments https://www.linpx.com/feed/