Nearly everything in JavaScript is an object. This includes arrays, Browser APIs, and functions. The only exceptions are null, undefined, strings, numbers, booleans, and symbols.
Unlike other object-oriented programming languages, JavaScript is not considered a class-based language. In JavaScript the class keyword is a helper function that makes existing JavaScript implementations more familiar to users of class-based programming.
We’ll demonstrate this by creating a class and checking the type.
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
class Student {
constructor() {
this.id = 1;
this.enrolled = true
const newObject = {};
}
isActive() {
console.log("Checking if active")
return this.enrolled
}
}
> s.isActive()
Checking if active
false
> s.isActive = function(){
... console.log("New isActive");
... return true;
... }
[Function (anonymous)]
> s.isActive()
New isActive
true
> s.__proto__.isActive()
Checking if active
undefined
> delete s.isActive
true
> s.isActive()
Checking if active
false
According to the documentation, JavaScript’s new keyword will first create an empty object. Within that object, it will set the __proto__
value to the constructor function’s prototype (where we set isActive). With __proto__
set, the new keyword ensures that this refers to the context of the newly created object. Previous commands shows that this.id and this.enrolled of the new object are set to the respective values. Finally, this is returned (unless the function returns its own object).
1
2
3
4
5
6
7
newObject = {
this.__proto__ = constructor() {this.id = 1; this.enrolled = true
const newObject = {};} isActive() { console.log("Checking if active")
return this.enrolled}
};