A typical JavaScript class (ES6)

with setter, getter, inheritance

source: https://coryrylan.com/blog/javascript-es6-class-syntax

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
class Person {
constructor(name) {
this._name = name;
}

get name() {
return this._name;
}

set name(newName) {
this._name = newName;
}

walk() {
console.log(this._name + ' is walking.');
}
}

class Programmer extends Person {
constructor(name, programmingLanguage) {
super(name);
this._programmingLanguage = programmingLanguage;
}

get programmingLanguage() {
return this._programmingLanguage;
}

set programmingLanguage(newprogrammingLanguage) {
this._programmingLanguage = newprogrammingLanguage;
}

writeCode() {
console.log(
this._name + ' is coding in ' + this._programmingLanguage + '.'
);
}
}

let bob = new Person('Bob');
bob.walk(); //Bob is walking.
//the usage of getter and setter
console.log(bob.name); //Bob
bob.name = "Aob";
console.log(bob.name); //Aob

let cory = new Programmer('Cory', 'JavaScript');
cory.walk(); //Cory is walking.
cory.writeCode(); //Cory is coding in JavaScript.
console.log(cory.name); //Cory

Clone object

https://www.samanthaming.com/tidbits/70-3-ways-to-clone-objects/

for-loop

Ref: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Loops_and_iteration

Pay attention to the difference between for-of loop and for-in loop

The following example shows the difference between a for...of loop and a for...in loop. While for...in iterates over property names, for...of iterates over property values:

1
2
3
4
5
6
7
8
9
10
const arr = [3, 5, 7];
arr.foo = 'hello';

for (let i in arr) {
console.log(i); // logs "0", "1", "2", "foo"
}

for (let i of arr) {
console.log(i); // logs 3, 5, 7
}

Capitalize String

Ref: https://stackoverflow.com/questions/1026069/how-do-i-make-the-first-letter-of-a-string-uppercase-in-javascript

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
// 10,889,187 operations/sec
function capitalizeFirstLetter(string) {
return string[0].toUpperCase() + string.slice(1);
}

// 10,875,535 operations/sec
function capitalizeFirstLetter(string) {
return string.charAt(0).toUpperCase() + string.slice(1);
}

// 4,632,536 operations/sec
function capitalizeFirstLetter(string) {
return string.replace(/^./, string[0].toUpperCase());
}

// 1,977,828 operations/sec
String.prototype.capitalizeFirstLetter = function() {
return this.charAt(0).toUpperCase() + this.slice(1);
}