Skip to content

Instantly share code, notes, and snippets.

@Abdallah-Abdelazim
Last active June 19, 2023 17:24
Show Gist options
  • Save Abdallah-Abdelazim/f709d0fd8fb93f39ede20b17b778d198 to your computer and use it in GitHub Desktop.
Save Abdallah-Abdelazim/f709d0fd8fb93f39ede20b17b778d198 to your computer and use it in GitHub Desktop.
Complete Object-Oriented JavaScript example (ES5).
function Person(first, last, age, gender, interests) {
this.name = {
first,
last
};
this.age = age;
this.gender = gender;
this.interests = interests;
};
function Teacher(first, last, age, gender, interests, subject) {
Person.call(this, first, last, age, gender, interests); // The call() method calls a function with a given this value and arguments provided individually.
this.subject = subject;
}
Teacher.prototype = Object.create(Person.prototype); // The Object.create() method creates a new object, using an existing object as the prototype of the newly created object.
Teacher.prototype.constructor = Teacher;
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.';
}
alert('Hello. My name is ' + prefix + ' ' + this.name.last + ', and I teach ' + this.subject + '.');
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment