Gary Guo

Learning never ends


  • Home

  • About

  • Tags

  • Categories

  • Archives

  • Sitemap

  • Search

Testing in JavaScript

Posted on 2018-03-21 | In JavaScript

Introduction

There are many ways to test and debug JavaScript code. Here I will note down some methods that I am using.

Methods

1. Create a HTML file with JavaScript code

Create a HTML file such as test.html with JavaScript code in local directory. Open the file directly

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
<script>
var test = 'Test string';
console.log(test);
alert("Hello, World!");
</script>
</head>
<body>
This is a test page.
</body>
</html>

2. Test with jsfiddle

  • Open site jsfiddle

  • Add the below code to HTML section

    1
    <div id="console-log"></div>
  • Add the below code to CSS section

    1
    2
    3
    4
    5
    .console-line
    {
    font-family: monospace;
    margin: 2px;
    }
  • Add the below code to JavaScript section and choose a jQuery library as the FRAMEWORK & EXTENSIONS

    1
    2
    3
    4
    5
    6
    7
    var consoleLine = "<p class=\"console-line\"></p>";

    console = {
    log: function (text) {
    $("#console-log").append($(consoleLine).html(text));
    }
    };
  • Choose Save button to save new fiddle, and bookmark the new URL

  • Now, you can add your code for testing.

    1
    2
    3
    var test = "Test String";
    console.log(test);
    alert("Hello, World!");

3. Test with Visual Studio Code and local web server

  • Install Node.js
  • Create a new folder for your project
  • Add a package.json file to the project folder

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    { 
    "name": "Demo",
    "version": "1.0.0",
    "description": "demo project.",
    "scripts": {
    "lite": "lite-server --port 10001",
    "start": "npm run lite"
    },
    "author": "",
    "license": "ISC",
    "devDependencies": {
    "lite-server": "^1.3.1"
    }
    }
  • Install the web server

    In a terminal window (command prompt in Windows) opened on your project folder, run this command:

    1
    npm install

    This will install lite-server (defined in package.json), a static server that loads index.html in your default browser and auto refreshes it when application files change.

  • Start the local web server

    Assuming you have an index.html file in your project folder. In the same terminal window (command prompt in Windows) run this command:

    1
    npm start

    Wait a second and index.html is loaded and displayed in your default browser served by your local web server!
    lite-server is watching your files and refreshes the page as soon as you make changes to any html, js or css files.
    And if you have VS Code configured to auto save (menu File / Auto Save), you see changes in the browser as you type!

    Notes:

    Do not close the command line prompt until you’re done coding in your app for the day
    It opens on http://localhost:10001 but you can change the port by editing the package.json file.

    That’s it. Now before any coding session just type npm start and you are good to go!

Reference

Visual Studio Code and local web server

Highlight ABAP Language in Hexo

Posted on 2018-03-21 | In ABAP

Background

The code highlighting functionality highlight.js is not enabled for ABAP language for Hexo by default. You can follow the below guide to enable it.

Setup

1. Update the file .\node_modules\highlight.js\lib\index.js under Hexo base folder, and add the below code

1
hljs.registerLanguage('abap', require('./languages/abap'));

2. Create a file .\node_modules\highlight.js\lib\languages\abap.js under Hexo base folder, and add the below code

The ABAP language syntax file is downloaded from GitHub, adjusted as below.

  • Add module.exports = at the beginning
  • Adjust the comment end tag from '\n' to '$'
  • Correct some typos in the keywords
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
module.exports = function(hljs) {
return {
case_insensitive: true,
keywords: {
keyword: 'ABBREVIATED ABS ABSTRACT FINAL ACCEPT ACCEPTING ACCORDING ACOS ACTUAL ADD ADD-CORRESPONDING ADDITIONS ADJACENT AFTER '
+'ALIASES ALL ALLOCATE ANALYZER AND APPEND APPENDING AS ASCENDING DESCENDING ASIN ASSIGN ASSIGNING ATAN ATTRIBUTE AUTHORITY-CHECK '
+'AVG BACK BACKGOUND BEFORE BETWEEN BIG LITTLE BINARY BIT BLANK BLOCK BREAK-POINT BUFFER BY BYPASSING BYTE BYTECHARACTER CALL CASE RESPECTING '
+'CASTING CEIL CENTERED CHANGE CHANGING CHARACTER CHECK CHECKBOX SYMBOL ICONLINE CLASS-DATA CLASS-EVENTS CLASS-METHODS CLEANUP CLEAR '
+'CLIENT CLOCK CLOSE CODE COL_BACKGROUND COL_HEADING COL_NORMAL COL_TOTAL COLLECT COLOR COLUMN COMMENT COMMIT COMMON COMMUNICATION COMPARING '
+'COMPONENT COMPONENTS COMPUTE CONCATENATE CONDENSE CONSTANTS CONTEXT CONTEXTS CONTINUE CONTROL CONTROLS CONVERSION CONVERT COS COSH COUNT COUNTRY '
+'COUNTY CREATE CURRENCY CURRENT CURSOR CUSTOMER-FUNCTION DATA DATABASE DATASET DATE DEALLOCATE DECIMALS DEFAULT UTF-8 NON-UNICODE DEFERRED '
+'DEFINE DEFINING DEFINITION DELETE DELETING DEMAND DESCENDING DESCRIBE DESTINATION DIALOG DIRECTORY DISTANCE DISTINCT DIVIDE DIVIDE-CORRESPONDING '
+'DUPLICATE DUPLICATES DURING DYNAMIC EDIT EDITOR-CALL ELSE ELSEIF ENCODING ENDING ENDON ENTRIES ERRORS EVENT EVENTS EXCEPTION EXCEPTIONS EXCEPTION-TABLE '
+'EXCLUDE EXCLUDING EXIT EXIT-COMMAND EXP EXPORT EXPORTING EXTENDED EXTENSION EXTRACT FETCH FIELD FIELD-GROUPS FIELDS NO FIELD-SYMBOLS FILTER FINAL FIND '
+'FIRST FLOOR FOR FORMAT FORWARD BACKWARD FOUND FRAC FRAME FREE FRIENDS FROM FUNCTION-POOL GET GIVING GROUP HANDLER HASHED HAVING HEADER HEADING '
+'HELP-ID HIDE HIGH LOW HOLD HOTSPOT ICON ID IGNORING IMMEDIATELY IMPLEMENTATION IMPORT IMPORTING IN INCLUDE INCREMENT INDEX INDEX-LINE INHERITING '
+'INIT INITIAL INITIALIZATION INNER INSERT INSTANCES INTENSIFIED INTERFACES INTERVALS INTO APPENDING INVERTED-DATE IS ITAB JOIN KEEPING '
+'KEY KEYS KIND LANGUAGE LAST LEADING LEAVE LEFT LEFT-JUSTIFIED CIRCULAR LEGACY LENGTH LIKE LINE LINE-COUNT LINES LINE-SELECTION '
+'LINE-SIZE LIST LIST-PROCESSING LOAD LOAD-OF-PROGRAM LOCAL LOCALE LOG LOG10 LOWER '
+'MARGIN MARK MASK MATCH MAX MAXIMUM MEMORY MESSAGE MESSAGE-ID MESSAGES METHODS MIN MOD MODE IF MODIFIER MODIFY MOVE MOVE-CORRESPONDING '
+'MULTIPLY MULTIPLY-CORRESPONDING NEW NEW-LINE NEW-PAGE NEXT NO- NODES NODETABLE NO-DISPLAY NO-GAP NO-GAPS NO-HEADING WITH-HEADING NON NO-SCROLLING '
+'SCROLLING NOT NO-TITLE WITH-TITLE NO-ZERO NP NS NUMBER OBJECT OBLIGATORY OCCURENCE OCCURENCES OCCURS OF OFF OFFSET ON ONLY ONOFF OPEN '
+'OPTION OPTIONAL OR ORDER OTHERS OUTER OUTPUT-LENGTH OVERLAY PACK PACKAGE PAGE LAST PAGES PARAMETER PARAMETERS PARAMETER-TABLE '
+'PART PERFORM PERFORMING PFN PF-STATUS PLACES POS_HIGH POS_LOW POSITION POSITIONS PRIMARY PRINT PRINT-CONTROL PRIVATE PROCESS PROGRAM PROPERTY '
+'PUBLIC PROTECTED PRIVATE PUSHBUTTON PUT QUICKINFO RADIOBUTTON RAISE RAISING RANGE RANGES READ RECEIVE RECEIVING REDEFINITION '
+'REF REFERENCE REFRESH REJECT RENAMING REPLACE REPLACEMENT REPORT RESERVE RESET RESOLUTION RESULTS RETURN RETURNING RIGHT RIGHT-JUSTIFIED '
+'ROLLBACK ROWS RUN SCAN SCREEN SCREEN-GROUP1 SCREEN-GROUP2 SCREEN-GROUP3 SCREEN-GROUP4 SCREEN-GROUP5 SCREEN-INPUT SCREEN-INTENSIFIED SCROLL '
+'SCROLL-BOUNDARY SEARCH SECTION SELECT SELECTION SELECTIONS SELECTION-SCREEN SELECTION-SET SELECTION-TABLE SELECT-OPTIONS SEND SEPARATED SET '
+'SHARED SHIFT SIGN SIN SINGLE DISTINCT SINH SIZE SKIP SORT SORTABLE SPECIFIED SPLIT SQL SQRT STABLE STAMP STANDARD START STARTING '
+'STATICS STEP-LOOP STOP STRLEN STRUCTURE SUBMIT SUBTRACT SUBTRACT-CORRESPONDING SUFFIX SUM SUPPLY SUPPRESS SYMBOLS SYSTEM-EXCEPTIONS TABLE TABLENAME '
+'TABLES TABLEVIEW TAN TANH TASK TEXT THEN TIME TIMES TITLE TITLEBAR TO TOPIC TOP-OF-PAGE TRAILING TRANSACTION TRANSFER TRANSLATE TRUNC TYPE '
+'TYPELIKE TYPE-POOL TYPE-POOLS TYPES ULINE UNION UNIQUE UNIT UNTIL UP UPDATE UPPER USER-COMMAND USING VALUE VALUES VARY VARYING '
+'VERSION VIA WAIT WHEN WHERE WINDOW WITH WORK WRITE XSTRLEN ZONE TRANSPORTING '
+'CA CN CO CP CS EQ GE GT LE LT NA NE'
+'START-OF-SELECTION START-OF-PAGE END-OF-PAGE END-OF-SELECTION AT ENDAT',
literal: 'abap_true abap_false',
built_in: 'DO FORM IF LOOP MODULE START-OF_FILE DEFINE WHILE BEGIN ENDDO ENDFORM ENDIF ENDLOOP ENDMODULE END-OF_FILE END-OF-DEFINITION ENDWHILE END'
+' METHOD ENDMETHOD CHAIN ENDCHAIN CASE ENDCASE FUNCTION ENDFUNCTION ELSEIF ELSE TRY ENDTRY CATCH '
},
contains: [
hljs.APOS_STRING_MODE,
hljs.NUMBER_MODE,
{
className: 'comment',
begin: '^[*]',
end: '$'
},
{
className: 'comment',
begin: '\b*"',
end: '$'
},
{
className: 'built_in',
begin: 'CALL +([A-Z])',
end:' +',
relevance: 10
}
]
}
};

3. Create a file .\node_modules\highlight.js\styles\abap.css under Hexo base folder, and add the below code

The ABAP language css file is downloaded from GitHub.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
/*
ABAP styles by Cassio Binkowski <cassioiks@gmail.com>
*/


.hljs {
display: block;
overflow-x: auto;
padding: 0.5em;
}
.hljs-keyword{
color: #0005fb;
}
.hljs-string{
color: #4da31e;
}
.hljs-comment{
color: #7c7879;
font-style: italic;
}
.hljs-built_in{
color: #000007;
font-weight: bold;
}
.hljs-literal{
color: #000007;
}
.hljs-subst {
color: black;
}
.hljs-number{
color: #5aceff;
}

4. Update the file \node_modules\hexo-util\highlight_alias.json under Hexo base folder

Add the below field-value mappings to alias object

1
2
"abap": "abap",
"ABAP": "abap",

Add the below value to languages array

1
"abap",

Result

Run hexo clean, hexo generate to generate the files. Below is the result with ABAP code highlighting.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
    select * from edisyn into table i_edisyn
where idoctyp eq doctyp
and cimtyp eq cimtyp.
if sy-subrc ne 0. "muß edisyn noch gemerged werden?
....
endif."EDISYN
* nun kann man aus der i_edisyn i_idocsyn füllen
loop at i_edisyn.
clear i_idocsyn.
move-corresponding i_edisyn to i_idocsyn.
move i_edisyn-posno to i_idocsyn-nr.
append i_idocsyn.
endloop.
endif."cimtyp

IF CL_IDOC_PORT_DEF=>SEND_ENHANCED_DOCU( ) = abap_true.
READ TABLE i_idocsyn WITH KEY SEGTYP = CL_IDOC_PORT_DEF=>ENH_SEGMENT TRANSPORTING NO FIELDS.
IF sy-subrc <> 0.
DESCRIBE TABLE i_idocsyn LINES COUNT.
READ TABLE i_idocsyn INDEX COUNT INTO l_LAST.
L_LAST-nr = L_LAST-nr + 1.
l_LAST-segtyp = CL_IDOC_PORT_DEF=>enh_segment.
CLEAR: L_LAST-parseg, L_LAST-mustfl, l_last-parpno.
L_LAST-occmin = 1.
L_LAST-hlevel = 01.
L_LAST-occmax = 999999.
APPEND L_LAST TO i_idocsyn.
move-corresponding L_LAST to i_edisyn.
move L_LAST to i_edisyn-posno.
append i_edisyn.
ENDIF.
ENDIF.

Reference

Add ABAP Language to highlight.js - GitHub

Backup Hexo using GitHub

Posted on 2018-03-20 | In Website

Assumption

You have already installed Git from https://git-scm.com/, installed Node.js, set up Hexo for your website, created an account in GitHub and created a repository there.

Requirement

You want to backup Hexo website data and restore it from anothter computer.

GitHub

Log on GitHub with your account. Create a branch such as backup for repository <account_name>.github.io

Backup

  • Open the file .gitignore in Hexo base folder, and check if it contains the below two entries. If no, add them to the file.

    1
    2
    /.deploy_git
    /node_modules

    Directory /.deploy_git contains the files after generation by command hexo generate. We don’t need to backup them.
    Directory /node_modules contains the node.js modules. We don’t need to backup them.

  • Execute the below command in the first backup

    1
    2
    3
    4
    5
    6
    # Init Git
    git init
    # Create the backup branch, and switch to the new branch
    git checkout -b backup
    # Link a remote repository to origin
    git remote add origin git@github.com:gary5496/gary5496.github.io.git
  • Execute the below command in each backup

    1
    2
    3
    4
    5
    6
    # Add the files and sub-directories in the current directory to staging area
    git add .
    # Commit the changes in the staging area to current branch
    git commit -m "commit_comments"
    # Push the backup branch to remote repository backup branch
    git push origin backup

Restore

If you need to restore the Hexo websites in another computer, you have to follow the Hexo setup guide to set up the Hexo in another computer first. Then, run the below command the clone the remote repository backup branch to the local directory.

1
2
# Clone the remote repository backup branch to the current directory
git clone -b backup git@github.com:gary5496/gary5496.github.io.git

Reference

http://blog.csdn.net/zk673820543/article/details/52698760
https://www.liaoxuefeng.com/wiki/0013739516305929606dd18361248578c67b8067c8c017b000
http://bbs.itheima.com/forum.php?mod=viewthread&tid=346526&ordertype=1

Shadow copy and Deep copy in JavaScript

Posted on 2018-03-20 | In JavaScript

Shadow Copy

In a shadow copy, the simple value properties of the source object is copied to the target object. However, for those object properties and methods of source object, the reference is assigned to the target object, instead of copy.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
var Chinese = {
nation: "Chinese",
birthPlace: ["Beijing", "Shanghai"]
};
var Doctor = {
career: "Doctor"
};
function extendCopy(p) {
var c = {};
for (var i in p) {
c[i] = p[i];
}
c.uber = p;
return c;
}

var Doctor = extendCopy(Chinese);

Doctor.birthPlace.push("Hongkong");
console.log(Doctor.birthPlace); //["Beijing", "Shanghai", "Hongkong"]
console.log(Chinese.birthPlace); //["Beijing", "Shanghai", "Hongkong"]

Deep Copy

In a deep copy, all the properties and methods of the source object is copied to the target object.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
var Chinese = {
nation: "Chinese",
birthPlace: ["Beijing", "Shanghai"]
};
var Doctor = {
career: "Doctor"
};
function deepCopy(p, c) {
var c = c || {};
for (var i in p) {
if (typeof p[i] === 'object') {
c[i] = (p[i].constructor === Array) ? [] : {};
deepCopy(p[i], c[i]);
} else {
c[i] = p[i];
}
}
return c;
}

var Doctor = deepCopy(Chinese);

Doctor.birthPlace.push("Hongkong");
console.log(Doctor.birthPlace); //["Beijing", "Shanghai", "Hongkong"]
console.log(Chinese.birthPlace); //["Beijing", "Shanghai"]

Reference

http://www.ruanyifeng.com/blog/2010/05/object-oriented_javascript_inheritance_continued.html

Prototype in JavaScript

Posted on 2018-03-20 | In JavaScript

Introduction

To simulate the OO class feature and implement the inheritance functionality in JavaScript, we have the below methods.

Methods

1. Inherit by calling parent constructor function

Using this method, all the properties and methods of parent function will be copied to the child objects.

Cons
  1. It will cost more memory if the parent function has lots of properties and methods or the inheritance chain is long.
  2. The prototype chain is not correct.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
function Animal(species){
this.species = species;
}

function Cat(name, color){
Animal.call(this, "Cat");
this.name = name;
this.color = color;
}
var cat1 = new Cat("Kitty","Yellow");

console.log(cat1.species); //Cat
console.log(cat1.__proto__ === Cat.prototype); //true
console.log(cat1.__proto__.__proto__ === Object.prototype); //true

In this case, the prototype chain will be:

new Cat() ----> Cat.prototype ----> Object.prototype ----> null

2. Inherit with one parent object

Using this method, one parent object will be created to save all the properties and methods of parent function, and the parent object is linked to __proto__ property of the child objects.

Pros:
  1. It will cost less memory when creating new child objects if the parent function has lots of properties and methods or the inheritance chain is long.
  2. The prototype chain is correct.
Cons:
  1. It will cost more memory when defining the child function.
  2. Since one parent object is linked to multiple child objects, the change to the parent object will affect multiple child objects.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
function Animal(species){
this.species = species;
}

function Cat(name, color){
this.name = name;
this.color = color;
}

Cat.prototype = new Animal({species: "Cat"});
Cat.prototype.constructor = Cat;

var cat1 = new Cat("Kitty","Yellow");
var cat2 = new Cat("Miao","White");

function Dog(name, color){
this.name = name;
this.color = color;
}

Dog.prototype = new Animal({species: "Dog"});
Dog.prototype.constructor = Dog;

var dog1 = new Dog("Wan","Yellow");

console.log(cat1.species.species); //Cat
console.log(cat1.__proto__ === cat2.__proto__); //true
console.log(cat1.__proto__ === Cat.prototype); //true
console.log(cat1.__proto__.__proto__ === Animal.prototype); //true
console.log(dog1.species.species); //Dog
console.log(Dog.prototype === Cat.prototype); //false

var sp = cat1.species;
sp.species = "New Cat";
console.log(cat1.species.species); //New Cat
console.log(cat2.species.species); //New Cat

In this case, the prototype chain will be:

new Cat() ----> Cat.prototype ----> Animal.prototype ----> Object.prototype ----> null

3. Inherit with new function object - Recommended

Using this method, all the properties and methods of parent function will be copied to the child objects.

Pros:
  1. It will cost less memory when defining the child function, since only one blank function object is created.
  2. The prototype chain is correct.
  3. The change to one child object will not affect other child objects.
Cons:
  1. It will cost more memory when creating new child objects, since all the properties and methods of parent function will be copied to the child objects, instead of linking one parent object to the child objects.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
function Animal(species){
this.species = species;
}

function Cat(name, color){
Animal.call(this, {species: "Cat"});
this.name = name;
this.color = color;
}

var F = function(){};
F.prototype = Animal.prototype;
Cat.prototype = new F();
Cat.prototype.constructor = Cat;

var cat1 = new Cat("Kitty","Yellow");
var cat2 = new Cat("Miao","White");

function Dog(name, color){
Animal.call(this, {species: "Dog"});
this.name = name;
this.color = color;
}

var F = function(){};
F.prototype = Animal.prototype;
Dog.prototype = new F();
Dog.prototype.constructor = Dog;

var dog1 = new Dog("Wan","Yellow");

console.log(cat1.species.species); //Cat
console.log(cat1.__proto__ === cat2.__proto__); //true
console.log(cat1.__proto__ === Cat.prototype); //true
console.log(cat1.__proto__.__proto__ === Animal.prototype); //true
console.log(dog1.species.species); //Dog
console.log(Dog.prototype === Cat.prototype); //false

var sp = cat1.species;
sp.species = "New Cat";
console.log(cat1.species.species); //New Cat
console.log(cat2.species.species); //Cat

In this case, the prototype chain will be:

new Cat() ----> Cat.prototype ----> Animal.prototype ----> Object.prototype ----> null

Notes

  • When create a new object using constructor function, the __proto__ of the new created object will point to the same object of ConstructorFunction.prototype.
1
2
3
4
5
6
function Animal(species){
this.species = species;
}

var animal = new Animal("Cat");
console.log(animal.__proto__ === Animal.prototype); //true
  • We can create a common function for the inheritance in the third method.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
function Animal(species){
this.species = species;
}

function Cat(name, color){
Animal.call(this, {species: "Cat"});
this.name = name;
this.color = color;
}

function inherits(Child, Parent) {
var F = function () {};
F.prototype = Parent.prototype;
Child.prototype = new F();
Child.prototype.constructor = Child;
Child.uber = Parent.prototype;
}

inherits(Cat, Animal);

var cat1 = new Cat("Kitty","Yellow");
var cat2 = new Cat("Miao","White");

function Dog(name, color){
Animal.call(this, {species: "Dog"});
this.name = name;
this.color = color;
}

inherits(Dog, Animal);

var dog1 = new Dog("Wan","Yellow");
  • We can define the new methods for the parent function and child function, in the prototype of the constructor function.
1
2
3
4
5
6
7
8
9
10
Animal.prototype.getspecies = function(){
return this.species.species;
};

Dog.prototype.getname = function(){
return this.name;
};

console.log(dog1.getspecies()); //Dog
console.log(dog1.getname()); //Wan

Reference

http://www.ruanyifeng.com/blog/2010/05/object-oriented_javascript_inheritance.html
Prototype Inheritance by Liao Xue Feng

12345

Gary Guo

23 posts
9 categories
19 tags
Links
  • Markdown Cheatsheet
  • JSFiddle
  • JavaScript - Liao XueFeng
  • Git - Liao XueFeng
  • Blog - Ruan YiFeng
© 2018 Gary Guo
Powered by Hexo
|
Theme — NexT.Gemini v6.0.5