Skip to content

Commit

Permalink
added examples of using prototypes
Browse files Browse the repository at this point in the history
Added example of using prototypes in objects
  • Loading branch information
chadsmith12 committed May 6, 2018
1 parent db30e17 commit ba116d5
Show file tree
Hide file tree
Showing 2 changed files with 50 additions and 0 deletions.
39 changes: 39 additions & 0 deletions prototypes/app.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
/* Prototypes in Javascript
* Each object in Javascript has a prototype. Prototype is also an object
*/

// object literals inherit from Object.prototype
// objects created by a constructor would be for example: Person.prototype

function Person(firstName, lastName, dob) {
this.firstName = firstName;
this.lastName = lastName;
this.birthday = new Date(dob);
}

// calculate age should go in the prototype
Person.prototype.getAge = function() {
const dateDiff = Date.now() - this.birthday.getTime();
const ageDate = new Date(dateDiff);

return Math.abs(ageDate.getUTCFullYear() - 1970);
}
Person.prototype.getFullName = function() {
return `${this.firstName} ${this.lastName}`;
}

Person.prototype.setLastName = function(lastName) {
this.lastName = lastName;
}

var person = new Person('Chad', 'Smith', '2-12-90');

console.log(person);
person.setLastName('Johnson');
console.log(person.getFullName());

// look at properties the object has
console.log(person.hasOwnProperty('lastName')); // yes
console.log(person.hasOwnProperty('getFullName')); // NO


11 changes: 11 additions & 0 deletions prototypes/index.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Sandbox</title>
</head>
<body>
<script src="app.js"></script>
</body>
</html>

0 comments on commit ba116d5

Please sign in to comment.