Skip to content

Instantly share code, notes, and snippets.

@Aldizh Aldizh/script.js
Last active Sep 20, 2019

Embed
What would you like to do?
Prototype Inheritance example javascript
// Every function created in javascript inherits from
// Object which is made of a constructor function and
// __proto__ which allows for sharing across multiples instances
// Defining a Person Object/Function
function Person(first, last, age, gender, interests) {
this.name = {
first,
last
};
this.age = age;
this.gender = gender;
this.interests = interests;
};
// Greeting here is shared across instances
Person.prototype.greeting = function() {
console.log('Hi! I\'m ' + this.name.first + '.');
};
// Teacher here inherits from Person with a small modification
function Teacher(first, last, age, gender, interests, subject) {
Person.call(this, first, last, age, gender, interests);
this.subject = subject;
}
// Ensure prototype is carried over the child
Teacher.prototype = Object.create(Person.prototype);
// Ensure that contructor is not anonymous
Teacher.prototype.constructor = Teacher;
// Observe the difference in greetings
var person = new Person('John', 'Doe', 30, 'male', ['soccer', 'ufc']);
var teacher = new Teacher('Dave', 'Griffiths', 31, 'male', ['football', 'cookery'], 'mathematics');
person.greeting();
teacher.greeting();
console.log('Is my greeting prototype the same? ', person.__proto__.greeting === teacher.__proto__.greeting)
// Now lets tweak the greeting prototype for Teacher Function/Class and check again
Teacher.prototype.greeting = function() {
var prefix;
if (this.gender === 'male' || this.gender === 'Male' || this.gender === 'm' || this.gender === 'M') {
prefix = 'Mr.';
} else if (this.gender === 'female' || this.gender === 'Female' || this.gender === 'f' || this.gender === 'F') {
prefix = 'Mrs.';
} else {
prefix = 'Mx.';
}
console.log('Hello. My name is ' + prefix + ' ' + this.name.last + ', and I teach ' + this.subject + '.');
};
person.greeting();
teacher.greeting();
console.log('Is my greeting prototype the same? ', person.__proto__.greeting === teacher.__proto__.greeting)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.