// Constructor Function
function Person(first, age) {
this.first = first;
this.age = age;
}
// Adds full to Person prototype, which can be accessed by all instances
Person.prototype.fullName = function() {
console.log(`${this.first} ${this.last} is ${this.age} years old`)
}
function Name(first, age, last) {
// Every instance of Name will now have a first and age property
Person.call(this, first, age); // creates context of "this"
this.last = last;
}
// We override the Name's prototype and delegate it on failed lookups to Person.prototype
// Without this line of code, the `Name` instance could not access the Person methods
Name.prototype = Object.create(Person.prototype)
// We can now add our own method to Name prototype
Name.prototype.isFrom = function(from) {
this.from = from;
console.log(`${this.first} ${this.last} is from ${this.from}`)
}
const chase = new Name("Chase", 31, "Isley")
chase.fullName(); // Chase Isley is 31 years old
/*
1) JavaScript checks if chase has an fullName property - it doesn't.
2) JavaScript then checks if Name.prototype has an fullName property
- it doesn't.
3) JavaScript then checks if Person.prototype has an fullName property
- it does so it calls it.
*/
const john = new Name("John", 35, "Jacob")
console.log(john.constructor); // logs Person.prototype
/*
1) JavaScript checks if john has a constructor property - it doesn't.
2) JavaScript then checks if Name.prototype has a constructor property
- it doesn't because it was deleted when we overwrote Name.prototype.
3) JavaScript then checks if Person.prototype has a constructor property
- it does so it logs that.
*/
// To fix the constructor property of Name to refer to Name's constructor and not Person (since we overwrote it above)
Name.prototype.constructor = Name;
console.log(chase.constructor); // Now logs Name constructor
// Can now call the isFrom Method on the Name Prototype
chase.isFrom("Las Vegas"); // Chase Isley is from Las Vegas
// Create Parent Class
class Person {
constructor(first, age) {
this.first = first;
this.age = age;
}
fullName() {
console.log(`${this.first} is ${this.age} years old`)
}
}
// Extend Person class to create 'Name' subclass
class Name extends Person {
constructor(first, age, last) {
super(first, age); // calls Person constructor
this.last = last;
}
isFrom(from) {
console.log(`${this.first} ${this.last} is from ${from}`)
}
}
let chase = new Name("Chase", 15, "Isley");
chase.isFrom("las Vegas"); // Chase Isley is from Las Vegas
chase.fullname(); // Chase is 15 years old
chase instanceof Name; // true
chase instanceof Person; // true