class
syntax makes writing and building objects easier/neat. 1'use strict'; // older version of Nodejs only allowed classes in Strcit mode
2
3class Person {
4 // constructor function
5 constructor (firstName, lastName, age) {
6 this.firstName = firstName;
7 this.lastName = lastName;
8 this.age = age;
9 }
10
11 // adding stuff to prototype to pass on to all instances of this class
12 // any methods that exist in the class will be automatically added to the prototype
13 greet() {
14 return `Hello ${this.firstName} ${this.lastName}`
15 }
16
17 details() {
18 return `${this.firstName} ${this.lastName} is ${this.age} year(s) old`
19 }
20}
21
22let jane = new Person('Jane', 'Davis', 28)
23
24// test
25console.info(jane) // Person { firstName: 'Jane', lastName: 'Davis', age: 28 }
26console.info(jane.greet) // [Function: greet]
27console.info(jane.greet()) // Hello Jane Davis
28
29console.info(jane.__proto__) // Person {}
30console.info(Object.getPrototypeOf(jane)) // Person {}
31
32// Get all methods/functions inside the class
33console.info(Object.getOwnPropertyNames(Person.prototype)) // [ 'constructor', 'greet', 'details' ]
34
35console.info(Person) // [Function: Person]
36console.info(jane.constructor) // [Function: Person]
is functionally equivalent to
1// constructor function
2function Person(firstName, lastName, age) {
3 this.firstName = firstName;
4 this.lastName = lastName;
5 this.age = age
6}
7
8// adding stuff to prototype to pass on to all instances of this class
9Person.prototype.greet = function() {
10 return `Hello ${this.firstName} ${this.lastName}`
11}
12
13Person.prototype.details = function() {
14 return `${this.firstName} ${this.lastName} is ${this.age} year(s) old`
15}
16
17let jane = new Person('Jane', 'Davis', 28)
18
19// test
20console.info(jane) // Person { firstName: 'Jane', lastName: 'Davis', age: 28 }
21console.info(jane.greet) // [Function]
22console.info(jane.greet()) // Hello Jane Davis
23
24console.info(jane.__proto__) // Person { greet: [Function], details: [Function] }
25console.info(Object.getPrototypeOf(jane)) // Person { greet: [Function], details: [Function] }
26
27console.info(Person) // [Function: Person]
Note that while jane.__proto__
in a normal constructor function gives us details for everything on the prototype Person { greet: [Function], details: [Function] }
, jane.__proto__
in a class constructor only gives the class Person {}
, not methods. Technically, there are no methods in JavaScript.
Notice that since classes are just syntactic sugar, there is no easy way of finding all (prototype) methods in a class. You can however use Object.getOwnPropertyNames(Foo.prototype)
to find all properties in a class prototype.