-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy path03-prototypes-explained.js
74 lines (64 loc) · 2.18 KB
/
03-prototypes-explained.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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
/**
* ******************************
* Prototypes Explained
* ******************************
**/
// Object.prototype - Object literals all have this prototype
// Person.prototype - Constructors have their own prototypes e.g. Persons.prototype but also have Object.prototype. This is known as prototype chain.
/**
* ********************
* Create a constructor
* ********************
**/
// Person constructor
function Person(firstName, lastName, dob) {
this.firstName = firstName;
this.lastName = lastName;
this.birthday = new Date(dob);
// this.calculateAge = function() {
// const diff = Date.now() - this.birthday.getTime();
// const ageDate = new Date(diff);
// return Math.abs(ageDate.getUTCFullYear() - 1970);
// };
}
/**
* ********************
* Create prototype methods
* ********************
**/
// Calculate age
Person.prototype.calculateAge = function() {
const diff = Date.now() - this.birthday.getTime();
const ageDate = new Date(diff);
return Math.abs(ageDate.getUTCFullYear() - 1970);
};
// Get full name
Person.prototype.getFullName = function() {
return `${this.firstName} ${this.lastName}`;
};
// Gets married last name
Person.prototype.getsMarried = function(newLastName) {
this.lastName = newLastName;
};
/**
* ********************
* Create object using the constructor
* ********************
**/
const john = new Person('John', 'Doe', '8-12-90');
const mary = new Person('Mary', 'Johnson', 'March 20 1978');
console.log(mary);
// The properties firstname, lastname & dob appear for mary as properties. If we look at the __Proto__ object we can now see the different functions created above in the Person.prototype avaibale to use as seen below.
/**
* ********************
* Log prototype methods
* ********************
**/
// Person.prototype
console.log(john.calculateAge()); // 27
console.log(mary.getFullName()); // Mary Johnson
mary.getsMarried('Smith'); // manipulate the object property to change the last name
console.log(mary.getFullName()); // Mary Smith
// Object.prototype
console.log(mary.hasOwnProperty('firstName')); // true
console.log(mary.hasOwnProperty('getFullName')); // false - this is in the prototype and not a property of its own