1// create div element by javascript with class
2
3var div = document.createElement('div');
4div.className = "div1";
5
1class Person {
2 constructor(name, age) {
3 this.name = name;
4 this.age = age;
5 }
6 displayInfo() {
7 return this.name + ' is' + this.age + " years old";
8 }
9}
10
11const Anthony = new Person('Anthony', 32);
1class Polygon {
2 constructor(height, width) {
3 this.height = height;
4 this.width = width;
5 }
6
7 get area() {
8 return this.calcArea();
9 }
10
11 calcArea() {
12 return this.height * this.width;
13 }
14}
15
16const square = new Polygon(10, 10);
17
18console.log(square.area);
1
2// to create a class named 'LoremIpsum':
3
4class LoremIpsum {
5
6 // a function that will be called on each instance of the class
7 // the parameters are the ones passed in the instantiation
8
9 constructor(a, b, c) {
10 this.propertyA = a;
11
12 // you can define default values that way
13 this.propertyB = b || "a default value";
14 this.propertyC = c || "another default value";
15 }
16
17 // a function that can influence the object properties
18
19 someMethod (d) {
20 this.propertyA = this.propertyB;
21 this.propertyB = d;
22 }
23}
24
25
26
27
28
29
30// you can then call it
31var loremIpsum = new LoremIpsum ("dolor", null, "sed");
32
33// at this point:
34// loremIpsum = { propertyA: 'dolor',
35// propertyB: 'a default value',
36// propertyC: 'sed' }
37
38loremIpsum.someMethod("amit");
39
40// at this point:
41// loremIpsum = { propertyA: 'a default value',
42// propertyB: 'amit',
43// propertyC: 'sed' }
44
45
46
47
48
49
50
51.
1let Person = class {
2 constructor(firstName, lastName) {
3 this.firstName = firstName;
4 this.lastName = lastName;
5 }
6}