forked from loiane/javascript-datastructures-algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path16-ES2015-ES6-Classes.js
89 lines (71 loc) · 1.7 KB
/
16-ES2015-ES6-Classes.js
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
// @ts-check
/* eslint-disable */
//* ****** EcmaScript 2015 (ES6): classes (https://goo.gl/UhK1n4)
class Book {
constructor(title, pages, isbn) {
this.title = title;
this.pages = pages;
this.isbn = isbn;
}
printIsbn() {
console.log(this.isbn);
}
}
let book = new Book('title', 'pag', 'isbn');
console.log(book.title); // outputs the book title
book.title = 'new title'; // update the value of the book title
console.log(book.title); // outputs the book title
// inheritance (https://goo.gl/hgQvo9)
class ITBook extends Book { // {1}
constructor(title, pages, isbn, technology) {
super(title, pages, isbn); // {2}
this.technology = technology;
}
printTechnology() {
console.log(this.technology);
}
}
let jsBook = new ITBook(
'Learning JS Algorithms',
'200',
'1234567890',
'JavaScript'
);
console.log(jsBook.title);
console.log(jsBook.printTechnology());
// getter and setters (https://goo.gl/SMRYsv)
class Person {
constructor(name) {
this._name = name; // {1}
}
get name() { // {2}
return this._name;
}
set name(value) { // {3}
this._name = value;
}
}
let lotrChar = new Person('Frodo');
console.log(lotrChar.name); // {4}
lotrChar.name = 'Gandalf'; // {5}
console.log(lotrChar.name);
lotrChar._name = 'Sam'; // {6}
console.log(lotrChar.name);
// using symbols for private atributes
var _name = Symbol();
class Person2 {
constructor(name) {
this[_name] = name;
}
get name() {
return this[_name];
}
set name(value) {
this[_name] = value;
}
}
let lotrChar2 = new Person2('Frodo');
console.log(lotrChar2.name);
lotrChar2.name = 'Gandalf';
console.log(lotrChar2.name);
console.log(Object.getOwnPropertySymbols(lotrChar2));