1class ClassMates{
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
11let classmate = new ClassMates("Mike Will",15);
12classmate.displayInfo(); // result: Mike Will is 15 years old!
1class Person {
2 constructor(name, age) {
3 this.name = name;
4 this.age = age;
5 }
6 present = () => { //or present(){
7 console.log(`Hi! i'm ${this.name} and i'm ${this.age} years old`)
8 }
9}
10let me = new Person("tsuy", 15);
11me.present();
12// -> Hi! i'm tsuy and i'm 15 years old.
1// Improved formatting of Spotted Tailed Quoll's answer
2class Person {
3 constructor(name, age) {
4 this.name = name;
5 this.age = age;
6 }
7 introduction() {
8 return `My name is ${name} and I am ${age} years old!`;
9 }
10}
11
12let john = new Person("John Smith", 18);
13console.log(john.introduction());
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);
1//use classes by initiating one like so:
2class MyClass {
3 constructor(FirstProperty, SecondProperty, etcetera) {
4 //The constructor function is called with the new class
5 //instance's parameters, so this will be called like so:
6 //var classExample = new MyClass("FirstProperty's Value", ...)
7 this.firstProperty = FirstProperty;
8 this.secondProperty = SecondProperty;
9 }
10 //creat methods just like functions:
11 method(Parameters) {
12 //Code Here
13 }
14 //getters are properties that are calculated when called, versus fixed
15 //variables, but still have no parenthesis when used
16 get getBothValues()
17 {
18 return [firstProperty, secondProperty];
19 }
20}
21//Note: this is all syntax sugar reducing the boilerplate versus a
22// function-defined object.
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.