Live Note

Remain optimistic

Class

1
2
3
4
5
6
7
8
9
10
11
// class factory
function classFactory(phone) {
return class {
getName() {
return phone
}
}
}

let _187 = classFactory("18720128815")
console.log(new _187().getName())

Calculated attribute name

1
2
3
4
5
6
7
class User {
["say" + "Hi"]() {
console.log("hi")
}
}

new User()["sayHi"]

Class field

1
2
3
4
5
6
7
8
// class field
class User {
name = "Edward" // is not at the prototype
}

const user = new User()
console.log(user.name) // Edward
console.log(User.prototype.name) // undefined

Extends — How the super run

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
let animal = {
name: "Animal",
eat() {
console.log(this.name + " eat")
},
}

let rabbit = {
__proto__: animal, // extends animal
eat() {
super.eat()
},
}

let err = {
__proto__: rabbit, // extends rabbit
name: "err obj",
eat() {
super.eat()
},
}

// super.eat() -> [[Rabbit.prototype]].eat
// -> super.eat -> [[Animal.prototype]].eat
// this -> err
err.eat()

class Animal {}
class Rabbit extends Animal {}
console.log(Rabbit.__proto__ === Animal) // class extends link
console.log(Rabbit.prototype.__proto__ === Animal.prototype) // prototype extends link

Prototype

change the basic class

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
let user = {
name: "Edward",
hello(name) {
console.log(`hi ${this.name}, this is ${name}`)
},
}

Function.prototype.defer = function (ms) {
let f = this
return function (...arg) {
setTimeout(() => f.apply(this, arg), ms)
}
}

user.hello = user.hello.defer(1000)
user.hello("Ejklfj") // will delay 1000ms

Magic of the instance of

1
2
3
4
5
6
7
8
class Animal {
static [Symbol.hasInstance](obj) {
if (obj.canEat) return true
}
}

let obj = { canEat: true }
console.log(obj instanceof Animal) // it will find from the [[Prototype]]

Static

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class User {
static staticMethod() {
console.log(this === User)
}
}

class Article {
constructor(title, date) {
this.title = title
this.date = date
}

static compare(articleA, articleB) {
return articleA.date - articleB.date
}
}

let articles = [
new Article("HTML", new Date(2019, 1, 1)),
new Article("Css", new Date(2019, 0, 1)),
]

articles.sort(Article.compare)
console.log(articles)

Class in ES2015

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
/**
* Class representing a point.
*/
class Point {
/**
* Create a point.
* @param {number} x - The x value.
* @param {number} y - The y value.
*/
constructor(x, y) {}

/**
* Get the x value.
* @return {number} The x value.
*/
getX() {}

/**
* Convert a string containing two comma-separated number into a point.
* @param {string} str - The string containing two comma-separated number.
* @return {Point} A point object.
*/
static fromStringStr(str) {}
}

extends

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
/**
* Class representing a point.
* @extends Point
*/
class Dot extends Point {
/**
* Create a dot.
* @param {number} x - The x value.
* @param {number} y - The y value.
* @param {number} width - The width of the dot.
*/
constructor(x, y, width) {
super(x, y)
}

/**
* Get the width of the dot.
* @return {number} The dot's width.
*/
getWidth() {}
}

@abstract

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
/**
* Foo.
* @constructor
*/
function Foo() {}

/**
* Check if is solid.
* @abstract
* @return {boolean}
*/
Foo.prototype.isSolid = function () {
throw new Error("Must be implemented by suclass.")
}

/**
* Bar.
* @constructor
* @arguments Foo
*/
function Bar() {}

/**
* Check if is solid.
* @return {boolean} Always return false.
*/
Bar.prototype.isSolid = function () {
return false
}

@assets

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
/**
* @constructor
*/
function Foo() {
/**
* @assets private
* @type {number}
*/
let foo = 0

/**
* @assets protected
* @type {string}
*/
this.bar = "1"

/**
* @assets package
* @type {string}
*/
this.barz = "2"

/**
* @assets public
* @type {string}
*/
this.barm = "3"
}

@author

1
2
3
4
/**
* @author Edward <wang.huiyang@outlook.com>
*/
function MyClass() {}

@callback

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
/**
* @class
*/
function Foo() {}

/**
* Send a request.
* @param {requestCallback} cb - The callback than handles the response.
*/
Foo.prototype.send = function (cb) {}

/**
* Callback
* @callback requestCallback
* @param {number} responseCode
* @param {string} responseMessage
*/

@event

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
/**
* @constructor
*/
function Foo() {}

/**
* Do some test.
* @fires Foo#test
*/
Foo.prototype.test = function () {}

/**
* Foo test.
* @event Foo#test
* @type {object}
* @property {boolean} isPass - Check if is pass.
*/

Null-aware operators

1
2
3
4
5
6
7
8
9
10
String foo = 'a string';
String bar; // Unassigned objects are null by default.

// Substitute an operator that makes 'a string' be assigned to baz.
String baz = foo ?? bar;

void updateSomeVars() {
// Substitute an operator that makes 'a string' be assigned to bar.
bar ??= 'a string';
}

Conditional property access

myObject?.someProperty equals to (myObject != null) ? myObject.someProperty : null.

1
2
3
4
5
6
// This method should return the uppercase version of `str`
// or null if `str` is null.
String upperCaseIt(String str) {
// Try conditionally accessing the `toUpperCase` method here.
return str?.toUpperCase();
}

Cascades

myObject.someMethod() will get the return value of the someMethod(), myObject..someMethod() will get the reference of the myObject.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class BigObject {
int anInt = 0;
String aString = '';
List<double> aList = [];
bool _done = false;

void allDone() {
_done = true;
}
}

BigObject fillBigObject(BigObject obj) {
// Create a single statement that will update and return obj:
return obj
..anInt = 1
..aString = "String!"
..aList = [3.0]
..allDone();
}
Read more »

EventUtil

为了在不同的浏览器中处理相同的事件,需要编写一段可以兼容大部分浏览器的代码。

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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
var EventUtil = {
addHandler: function (element, type, handler) {
//添加事件
if (element.addEventListener) {
element.addEventListener(type, handler, false) //使用DOM2级方法添加事件
} else if (element.attachEvent) {
//使用IE方法添加事件
element.attachEvent("on" + type, handler)
} else {
element["on" + type] = handler //使用DOM0级方法添加事件
}
},

removeHandler: function (element, type, handler) {
//取消事件
if (element.removeEventListener) {
element.removeEventListener(type, handler, false)
} else if (element.detachEvent) {
element.detachEvent("on" + type, handler)
} else {
element["on" + type] = null
}
},

getEvent: function (event) {
//使用这个方法跨浏览器取得event对象
return event ? event : window.event
},

getTarget: function (event) {
//返回事件的实际目标
return event.target || event.srcElement
},

preventDefault: function (event) {
//阻止事件的默认行为
if (event.preventDefault) {
event.preventDefault()
} else {
event.returnValue = false
}
},

stopPropagation: function (event) {
//立即停止事件在DOM中的传播
//避免触发注册在document.body上面的事件处理程序
if (event.stopPropagation) {
event.stopPropagation()
} else {
event.cancelBubble = true
}
},

getRelatedTarget: function (event) {
//获取mouseover和mouseout相关元素
if (event.relatedTarget) {
return event.relatedTarget
} else if (event.toElement) {
//兼容IE8-
return event.toElement
} else if (event.formElement) {
return event.formElement
} else {
return null
}
},

getButton: function (event) {
//获取mousedown或mouseup按下或释放的按钮是鼠标中的哪一个
if (document.implementation.hasFeature("MouseEvents", "2.0")) {
return event.button
} else {
switch (
event.button //将IE模型下的button属性映射为DOM模型下的button属性
) {
case 0:
case 1:
case 3:
case 5:
case 7:
return 0 //按下的是鼠标主按钮
case 2:
case 6:
return 2 //按下的是中间的鼠标按钮
case 4:
return 1 //鼠标次按钮
}
}
},

getWheelDelta: function (event) {
//获取表示鼠标滚轮滚动方向的数值
if (event.wheelDelta) {
return event.wheelDelta
} else {
return -event.detail * 40
}
},

getCharCode: function (event) {
//以跨浏览器取得相同的字符编码,需在keypress事件中使用
if (typeof event.charCode == "number") {
return event.charCode
} else {
return event.keyCode
}
},
}

eval()

eval 可以解析任何字符串变成 JS:

1
2
3
var str = "function testFunction() {console.log('test');}"
eval(str)
testFunction() //'test'

JSON.parse()

JSON.parse 只能解析 JSON 形式的字符串变成 JS,安全性比 eval 高一些。
字符串中的属性要严格加上引号

1
2
3
let str = '{ "name" : "hello" }'
let json = JSON.parse(str)
json.name //'hello'
Read more »