What can JavaScript do?

JavaScript can change HTML elements content.

1
2
3
<p id="demo">JavaScript can change HTML content.</p>

<button type="button" onclick='document.getElementById("demo").innerHTML = "Hello JavaScript!"'>Click Me!</button>

JavaScript can change HTML elements attributes.

1
2
3
<button onclick="document.getElementById('myImage').src='pic_bulbon.gif'">Turn on the light</button>

<img id="myImage" src="pic_bulboff.gif" style="width:100px">

JavaScript can show and hide HTML elements.

1
2
3
<p id="demo">JavaScript can hide HTML elements.</p>

<button type="button" onclick="document.getElementById('demo').style.display='none'">Click Me!</button>
1
2
3
<p id="demo" style="display:none">Hello JavaScript!</p>

<button type="button" onclick="document.getElementById('demo').style.display='block'">Click Me!</button>

JavaScript can change CSS style.

1
2
3
<p id="demo">JavaScript can change the style of an HTML element.</p>

<button type="button" onclick="document.getElementById('demo').style.fontSize='35px'">Click Me!</button>

JavaScript Insert

  1. internal element <head>

    1
    2
    3
    4
    5
    6
    7
    <head>
    <script>
    function myFunction() {
    document.getElementById("demo").innerHTML = "Paragraph changed.";
    }
    </script>
    </head>
  2. internal element <body>

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    <body>

    <h2>Demo JavaScript in Body</h2>

    <p id="demo">A Paragraph.</p>

    <button type="button" onclick="myFunction()">Try it</button>

    <script>
    function myFunction() {
    document.getElementById("demo").innerHTML = "Paragraph changed.";
    }
    </script>

    </body>
  3. external URL

    1
    <script src="https://www.w3schools.com/js/myScript.js"></script>
  4. external file

    1
    <script src="/js/myScript.js"></script>

Call JS Through Python

1
2
3
function f(){
return 'Hello'
}
1
2
3
4
5
6
7
import execjs
with open('test.js', 'r', encoding='utf-8') as f:
js_code = f.read()

s = execjs.compile(js_code).call('f')

print(s)

Variables

We can use var, let, const to define a variable.

1
2
3
4
5
var _a = '1', $b = 2,
变量 = '你好',
d = 100;

console.log(_a, $b, 变量, d) //1 2 你好 100
  • var

    Firstly, we should know JS interpreter will declare all var variables at beginning no matter they declares at the end of the file.

    1
    2
    3
    console.log(a)  //undefined

    var a = 100

    var defines a local variable.

    1
    2
    3
    4
    5
    6
    7
    8
    9
    function test(){
    var a = 1;
    b = 2;
    }

    test()

    console.log(a) //ReferenceError: a is not defined
    console.log(b) //2
  • let

    The let variables solve the weak point of var variables that can be use before declare them.

operators

equal

1
2
3
4
5
6
7
// Is value equal?
console.log(1 == "1") //true
//Is value and type equal?
console.log(1 === "1") //false

console.log(1 != "1") //false
console.log(1 !== "1") //true

and, or, not

1
2
3
console.log(true && false)  //false
console.log(true || false) //true
console.log(!true) //false

Data Types

Primitive types

Number, String, Boolean, null, undefined, NaN are the primitive types.

There are some differences between assigning the primitive variables and object variables.

1
2
3
4
var a = 10
var b = a
a=20
console.log(a, b) //20 10 the value of the variable a was changed to 20, but b was changed.

quote type

Object is the quote type.

1
2
3
4
5
6
7
var c = {
age: 20
}
var d = c
c.age = 100
console.log(c.age, d.age) //100 100 the value of the variables c.age and d.age were changed.

**The reason is that the value of an object variable is the object’s address. **

Condition

1
2
3
4
5
6
if (1 > 2){
console.log(true)
}
else {
console.log(false)
}

Function

the address of a function

1
2
3
4
5
var a = function (){    //anonymous function
console.log("Hello world")
}
a() //Hello world
//The variable a holds the address of the function defined above.

the returning value of a comma expression

Comma expressions are evaluated from left to right, and the result is the value of the last expression

1
2
3
4
5
6
function f(){
var b = 2;
return b--, b-1; //The function subtracts 1 from b two times, then returns the result.
}

console.log(f()) //0

the hidden argument

There is a hidden argument in a function.

1
2
3
4
5
6
function f(){
a = arguments
console.log(a)
}

f(1,2,3,4) //[Arguments] { '0': 1, '1': 2, '2': 3, '3': 4 }

Immediately Invoked Function Expression(IIFE)

We can add two sets of parentheses to write an IIFE: one to define the function, and the other to invoke it.

1
2
3
4
5
6
7
8
9
10
11
(function (){
console.log("Immediately Invoked Function Expression(IIFE) ")
})()

(function (){
console.log("Immediately Invoked Function Expression(IIFE) ")
}())

!function (){
console.log("Immediately Invoked Function Expression(IIFE) ")
}()

Function Hoisting

The JS interpreter declares the function firstly and then invokes themn.

1
2
3
4
5
6
7
8
9
f()     //World

function f(){
console.log("Hello")
}

function f(){
console.log("World")
}

this

1
2
3
4
5
6
7
8
9
10
11
12
function f(){
console.log(this)
}
f() //this === window, f() === window.f()

var t = {
name : 'ferry',
test: function(){
console.log(this.name)
}
}
t.test() //ferry, Now this === t

As you can see, the address of this is the address of previous function.

call()

call(target, arg1, arg2): the call function can change the address of this

1
2
3
4
5
6
7
8
9
10
11
12
13
14
function Teacher(name, age, major) {
this.name = name;
this.age = age;
this.major = major;
this.teach = function () {
console.log(`${this.name} teaches students ${this.major}`)
}
}

ferry = new Teacher('ferry', 24, 'JavaScrip')
faye = new Teacher('faye', 18, 'Python')

faye.teach() //faye teaches students Python
faye.teach.call(ferry) //ferry teaches students JavaScrip

setTimeout(), setInterval()

setTimeout(function name(params){}, ms)

1
2
3
y = setInterval(function(){
console.log("Hello")
}, 2000)

we can use cleanInerval(number) cleaning the timer.

eval()

The eval() can execute the string type of JavaScript code.

1
2
s = "console.log('Hello World')"
eval(s)

But the string type of JavaScript usually is encrypted.

Arrow function

The arrow function is a omission of general function.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
a = function (){
console.log("Hello")
}
//omit the Function keyword and add an arrow
b = ()=>{
console.log("World")
}
//when there is one parameter
c = p =>{
console.log(p)
}
c("I'm ferry")
//when there are two parameters
d = (e, f)=>{
return e+f;
}
console.log(d(1, 2)); //3
//when there is one statement of return
g = (h, i)=> h+i
console.log(g(1,2)) //3

Loop

The i<10, j<15 is a comma expressions that return the value of the last expression.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
for(i=0, j=0; i<10, j<15; i++, j++){
console.log(i, j);
}

// 0 0
// 1 1
// 2 2
// 3 3
// 4 4
// 5 5
// 6 6
// 7 7
// 8 8
// 9 9
// 10 10
// 11 11
// 12 12
// 13 13
// 14 14
1
2
3
4
5
6
7
8
a = ['a', 'ferry', 1, 'reverse engineering']
for(i in a){
console.log(a[i])
}
// a
// ferry
// 1
// reverse engineering

Date

1
2
3
4
5
var t = Date.now()
console.log(t)

var d = new Date().getTime()
console.log(d)

Object

like dictionary object

An object consists of variables, functions, and objects.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
var obj1 = {
'name': 'ferry',
age: 28,
gender: 'male',
eat: function (){
return 'I like eating'
},
obj2: {
hobby: 'football',
job: 'programmer'
}
}

console.log(obj1.name, obj1.eat(), obj1.obj2.job) //ferry I like eating programmer
console.log(obj1['age'], obj1['eat'](), obj1['obj2']['hobby']) //28 I like eating football

JS confusion

We have to focus on the second method accessing variables and functions. The string type can refer to the name of them. Therefore, we can change the form of the string, such as encryption

Encryption

1
2
3
4
5
6
7
8
9
10
11
12
//First of all, we encrypt the string substring
s2 = 'substring'.split('')
s3 = []
s2.forEach(function (a, b){ //The parameter a refers to the current element of the array s2, and b refers to the index of that element.
s3.push(a.charCodeAt(0)); //change to ASCII form
})
console.log(s3)
// [
// 115, 117, 98, 115,
// 116, 114, 105, 110,
// 103
// ]

Decryption

1
2
3
4
5
6
7
8
9
10
s4 = [
115, 117, 98, 115,
116, 114, 105, 110,
103
]
s5 = []
for(i=0; i<s4.length;i++){
s5.push(String.fromCharCode(s4[i])); //decryption
}
console.log(s5.join('')) //substring

JS confusion

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
//Origin JS
s = 'password: 123456'
t = s['substring'](10,)
console.log(t) //123456


// JS Confusion
s4 = [
115, 117, 98, 115,
116, 114, 105, 110,
103
]
s5 = []
for(i=0; i<s4.length;i++){
s5.push(String.fromCharCode(s4[i])); //decryption
}
console.log(s5.join('')) //substring
v = s[s5.join('')](10,)
console.log(v) //123456

Constructor

We can use Teacher constructor function to create objects.

1
2
3
4
5
6
7
8
9
10
11
function Teacher(name, age, major){
this.name = name;
this.age = age;
this.major = major;
this.teach = function (){
console.log(`${this.name} teaches students ${this.major}`)
}
}

ferry = new Teacher('Ferry', 24, 'JavaScript')
ferry.teach() //Ferry teaches students JavaScript

prototype object

Sometimes, we need to add functions to the original object. Therefore, we need to use prototype keyword.

1
2
3
4
5
6
7
8
//prototype object
Teacher.prototype.hobby = function (hobby_name){
this.hobby_name = hobby_name
console.log(`${this.name} likes ${this.hobby_name}`)
}

faye = new Teacher('Faye', 23, 'Python')
faye.hobby('football') //Faye likes football

Teacher.prototype is an object belonging to a attribute of Teacher constructor function. It acts as the prototype of all instances created using new Teacher().

1
2
Teacher.prototype === ferry.__proto__
true

ferrt.__proto__ is an object belonging to instances created using new Teacher(). It points to the prototype of its constructor function.

ferry.__proto__ —> Teacher.prototype, Teacher.__proto__ —> Function.prototype

Besides, Teacher.prototype.__proto__ —> Object.prototype

┌────────────┐
│ Function │ ← 所有函数的构造器
└─────┬──────┘


┌──────────────────┐
│ Teacher │ ← (构造函数)
__proto__ ─────────▶ Function.prototype
│ prototype ─────────▶ (Teacher.prototype)
└──────────────────┘


┌─────────────┴─────────────┐
│ Teacher.prototype │
│ (一个普通对象) │
__proto__ ─────────▶ Object.prototype
└─────────────┬─────────────┘


┌────────────────────────┐
│ ferry │ ← 实例对象
__proto__ ─────────────▶ Teacher.prototype
└────────────────────────┘

jQuery

CSS selector

Using CSS selector to select the element

1
2
$('#name')[0]
<div id=​"name">​ ferry ​</div>​

ajax() method

we need to pass a object as the parameter for ajax method

1
2
3
4
5
6
$.ajax({
url: "http://xxx",
type: "get",
data: { request parameters },
success: function (res){ browser runs this function when gets response }
})

Scope

The Scope mains the effectiveness range of variables or functions in the code.

Range: block scope < function scope < global scope

Priority: block scope > function scope > global scope

var

Variables declared by var have a function scope.

1
2
3
4
5
6
7
8
9
10
11
var a = 3 //variable a is in the global scope.

function test(b){ //Both variable a and b are in the function scope.
var c = 1
return {
b: b,
c: c,
}
}

console.log(a, test(2).b, test().c) //3 2 1

let

Variables declared by let have a block scope.

1
2
3
4
5
6
7
8
function f(){
if (1){
let a = 1;
console.log(a) //1
}
console.log(a) //error
}
f()

declare by noting

Variables declared by nothing have a global scope.

1
2
3
4
5
function f(){
a = 1; //global scope
}
f()
console.log(a) //1

Closure

There is a encrypt function in another function scope. We cannot access that encrypt function outside of the function scope.

We have to record the address of that encrypt function so that we can access it outside its original scope.

There are two method to record:

  1. using a global variable

    1
    2
    3
    4
    5
    6
    7
    8
    (function f(){
    function encrypt(){
    console.log("This is an encrypt function.")
    }
    global_variable = encrypt
    })()

    global_variable() //This is an encrypt function.
  2. return the address directly

    1
    2
    3
    4
    5
    6
    7
    8
    global_variable = (function f(){
    function encrypt(){
    console.log("This is an encrypt function.")
    }
    return encrypt
    })()

    global_variable() //This is an encrypt function.