es6类的使用

  |  
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
'use strict';
// 类的由来 原始js 方法声明
// function Book(title, pages, isbin) {
// this.title = title;
// this.pages = pages;
// this.isbin = isbin;
// }

// Book.prototype.init = function() { // 只能定义public 方法
// console.log(this.title);
// };

// let book = new Book('title', 'page', 'isbin');

// book.init();


// es6 类声明
class Book {
constructor(title, pages, isbin) {
this.title = title;
this.pages = pages;
this.isbin = isbin;
}

init() {
console.log(this.title);
}
}

// let book = new Book('title', 'page', 'isbin');
// console.log(book.title);// 输出 title
// book.title = 'new title';
// console.log(book.title); // 输出 new title
// book.init();// 输出 new title

// 继承
class IBook extends Book {
constructor(title, pages, isbin, newBook) {
super(title, pages, isbin);
this._newBook = newBook;
}

// 也可以使用get set属性存储器 可以进行一些其他参数处理
get newBook() {
return this._newBook;
}
set newBook(value) {
this._newBook = `aaaa${value}`;
}

}

let iBook = new IBook('title', 'page', 'isbin', '新参数');

console.log(iBook.newBook); // 新参数
iBook.newBook = '新参数2';
console.log(iBook.newBook); // aaaa新参数2

iBook.init(); // 输出 title

Class 的基本语法

文章目录