repl.it
@ManavMisra/

Object Literal vs Function Constructor

Nodejs

No description

fork
loading
Files
  • index.js
index.js
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
51
52
53
54
// Fxn. Constructor
function Student(id, name, age) {
  this.id = id;
  this.name = name;
  this.age = age;
  // We could add methods inside of here...but that results in every student having their own copy of that method
};

Student.prototype.displayInfo = function() {
    return `${this.name} says: ID: ${this.id}, Name: ${this.name}`;
}

Student.prototype.displayAge = function() {
  return `${this.name} is ${this.age} years old`;
}

const testStudent = new Student(1, 'James', 38);
const friendlyStudent = new Student(1, "john", 33);
const lyingStudent = new Student(3, "Stan", 19);

// IF we give an individual student it's own method of the same name as one in the PROTOTYPE, then this will get called, thereby overriding the PROTOTYPE version.
lyingStudent.displayAge = function() {
    return `${this.name} is 21 years old`;
}

// When we run a method, JS checks if the individual has an implementation of that method.
// If not, then it checks the PROTOTYPE.
console.log(testStudent.displayAge());
console.log(friendlyStudent.displayAge());
console.log(lyingStudent.displayAge());

/**
 * JS checks the currently instantiated student for a method.
 * If it finds it, it runs it.
 * If not, it checks on the PROTOTYPE, and tries to run a method of that name there.
 * This continues all the way 'up the chain' to something called Object.prototype...
 */
testStudent.displayInfo = function() {
  return `${this.name} says: none of yur business!`;
}

console.log(testStudent.displayInfo());
console.log(friendlyStudent.displayInfo());

console.log(testStudent);

// We utilize the PROTOTYPE to create all the students instead of creating separate OBJECT LITERALS for each student

/**
 * For 1 thing, what happens if we need to add functionality to each student? 
 * With OBJECT LITERAL, we would need to iterate and add some new value to all of them, etc.
 */

// Currently, we are adding a separate 'copy' of `displayInfo()` to each of the students!...
?