|
| 1 | +/** |
| 2 | + * ****************************** |
| 3 | + * Prototypes Explained |
| 4 | + * ****************************** |
| 5 | + **/ |
| 6 | + |
| 7 | +// Object.prototype - Object literals all have this prototype |
| 8 | +// Person.prototype - Constructors have their own prototypes e.g. Persons.prototype but also have Object.prototype. This is known as prototype chain. |
| 9 | + |
| 10 | +/** |
| 11 | + * ******************** |
| 12 | + * Create a constructor |
| 13 | + * ******************** |
| 14 | + **/ |
| 15 | + |
| 16 | +// Person constructor |
| 17 | +function Person(firstName, lastName, dob) { |
| 18 | + this.firstName = firstName; |
| 19 | + this.lastName = lastName; |
| 20 | + this.birthday = new Date(dob); |
| 21 | + // this.calculateAge = function() { |
| 22 | + // const diff = Date.now() - this.birthday.getTime(); |
| 23 | + // const ageDate = new Date(diff); |
| 24 | + // return Math.abs(ageDate.getUTCFullYear() - 1970); |
| 25 | + // }; |
| 26 | +} |
| 27 | + |
| 28 | +/** |
| 29 | + * ******************** |
| 30 | + * Create prototype methods |
| 31 | + * ******************** |
| 32 | + **/ |
| 33 | +// Calculate age |
| 34 | +Person.prototype.calculateAge = function() { |
| 35 | + const diff = Date.now() - this.birthday.getTime(); |
| 36 | + const ageDate = new Date(diff); |
| 37 | + return Math.abs(ageDate.getUTCFullYear() - 1970); |
| 38 | +}; |
| 39 | + |
| 40 | +// Get full name |
| 41 | +Person.prototype.getFullName = function() { |
| 42 | + return `${this.firstName} ${this.lastName}`; |
| 43 | +}; |
| 44 | + |
| 45 | +// Gets married last name |
| 46 | +Person.prototype.getsMarried = function(newLastName) { |
| 47 | + this.lastName = newLastName; |
| 48 | +}; |
| 49 | + |
| 50 | +/** |
| 51 | + * ******************** |
| 52 | + * Create object using the constructor |
| 53 | + * ******************** |
| 54 | + **/ |
| 55 | +const john = new Person('John', 'Doe', '8-12-90'); |
| 56 | +const mary = new Person('Mary', 'Johnson', 'March 20 1978'); |
| 57 | + |
| 58 | +console.log(mary); |
| 59 | +// 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. |
| 60 | + |
| 61 | +/** |
| 62 | + * ******************** |
| 63 | + * Log prototype methods |
| 64 | + * ******************** |
| 65 | + **/ |
| 66 | +// Person.prototype |
| 67 | +console.log(john.calculateAge()); // 27 |
| 68 | +console.log(mary.getFullName()); // Mary Johnson |
| 69 | +mary.getsMarried('Smith'); // manipulate the object property to change the last name |
| 70 | +console.log(mary.getFullName()); // Mary Smith |
| 71 | + |
| 72 | +// Object.prototype |
| 73 | +console.log(mary.hasOwnProperty('firstName')); // true |
| 74 | +console.log(mary.hasOwnProperty('getFullName')); // false - this is in the prototype and not a property of its own |
0 commit comments