Skip to content

Commit 32e9da0

Browse files
committed
ES6 classes example
1 parent a26b00e commit 32e9da0

File tree

2 files changed

+100
-0
lines changed

2 files changed

+100
-0
lines changed

chapter01/16-ES6Classes.html

+10
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
<!DOCTYPE html>
2+
<html>
3+
<head lang="en">
4+
<meta charset="UTF-8">
5+
<title></title>
6+
</head>
7+
<body>
8+
<script type="text/javascript" src="16-ES6Classes.js"></script>
9+
</body>
10+
</html>

chapter01/16-ES6Classes.js

+90
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,90 @@
1+
// ES6 classes
2+
class Book {
3+
constructor (title, pages, isbn) {
4+
this.title = title;
5+
this.pages = pages;
6+
this.isbn = isbn;
7+
}
8+
printIsbn(){
9+
console.log(this.isbn);
10+
}
11+
}
12+
13+
let book = new Book('title', 'pag', 'isbn');
14+
15+
console.log(book.title); //outputs the book title
16+
17+
book.title = 'new title'; //update the value of the book title
18+
19+
console.log(book.title); //outputs the book title
20+
21+
22+
//inheritance
23+
class ITBook extends Book {
24+
25+
constructor (title, pages, isbn, technology) {
26+
super(title, pages, isbn);
27+
this.technology = technology;
28+
}
29+
30+
printTechnology(){
31+
console.log(this.technology);
32+
}
33+
}
34+
35+
let jsBook = new ITBook('Learning JS Algorithms', '200', '1234567890', 'JavaScript');
36+
37+
console.log(jsBook.title);
38+
console.log(jsBook.printTechnology());
39+
40+
//getter and setters
41+
class Person {
42+
43+
constructor (name) {
44+
this._name = name;
45+
}
46+
47+
get name() {
48+
return this._name;
49+
}
50+
51+
set name(value) {
52+
this._name = value;
53+
}
54+
}
55+
56+
let lotrChar = new Person('Frodo');
57+
console.log(lotrChar.name);
58+
lotrChar.name = 'Gandalf';
59+
console.log(lotrChar.name);
60+
61+
lotrChar._name = 'Sam';
62+
console.log(lotrChar.name);
63+
64+
65+
//using symbols for private atributes
66+
67+
var _name = Symbol();
68+
class Person2 {
69+
70+
constructor (name) {
71+
this[_name] = name;
72+
}
73+
74+
get name() {
75+
return this[_name];
76+
}
77+
78+
set name(value) {
79+
this[_name] = value;
80+
}
81+
}
82+
83+
let lotrChar2 = new Person2('Frodo');
84+
console.log(lotrChar2.name);
85+
lotrChar2.name = 'Gandalf';
86+
console.log(lotrChar2.name);
87+
88+
console.log(Object.getOwnPropertySymbols(lotrChar2));
89+
90+
//http://davidvujic.blogspot.com.br/2015/03/what-wait-really-oh-no-a-post-about-es6-classes-and-privacy.html

0 commit comments

Comments
 (0)