ES6 Class

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)