Skip to content

Instantly share code, notes, and snippets.

@eamon0989
Last active August 2, 2021 14:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save eamon0989/98b40ecfff48366f00b35c62945492d6 to your computer and use it in GitHub Desktop.
Save eamon0989/98b40ecfff48366f00b35c62945492d6 to your computer and use it in GitHub Desktop.
function Grandfather(name, age, job) {
this.name = name;
this.age = age;
this.job = job;
}
Grandfather.prototype.aboutMe = function() {
console.log(`I'm ${this.name}, I'm ${this.age} years old and I'm ${this.job === 'retired' ? '' : 'a '}${this.job}.`);
};
let grandad = new Grandfather('Jonathan', 80, 'retired');
grandad.aboutMe(); // I'm Jonathan, I'm 80 years old and I'm retired.
console.log(grandad); // Grandfather { name: 'Jonathan', age: 80, job: 'retired' }
function Father(name, age, job) {
Grandfather.call(this, name, age, job);
}
Father.prototype = Object.create(Grandfather.prototype);
let dad = new Father('John', 40, 'coder');
dad.aboutMe(); // I'm John, I'm 40 years old and I'm a coder.
function Son(name, age, job) {
Father.call(this, name, age, job);
}
Son.prototype = Object.create(Father.prototype);
let son = new Son('Johnny', 18, 'student');
son.aboutMe(); // I'm Johnny, I'm 18 years old and I'm a student.
console.log(son instanceof Son); // true
console.log(Father.prototype.isPrototypeOf(Son.prototype)); // true
console.log(Grandfather.prototype.isPrototypeOf(Son.prototype)); // true
console.log(son); // Grandfather { name: 'Johnny', age: 18, job: 'student' }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment