Purpose: inherit only the object keys, not the ones inherited
Two constructor: Person and Teacher. Teacher is inheriting properties using prototypal inheritance.
Height and weight are the two keys inherited from person to teacher.
To my understanding for ... in loops through all the keys in the object as well as keys inherited. Therefore hasOwnProperty is used to filter the properties only available within the Teacher object. However the code outputs all the properties including height and weight which it should not.
/* eslint-disable no-console */
function Person(first, last, age, gender, interests, weight, height) {
this.name = {
first,
last,
};
this.age = age;
this.gender = gender;
this.interests = interests;
this.weight = weight;
this.height = height;
}
Person.prototype.greeting = () => {
console.log(`Hi! I'm ${this.name.first}.`);
};
function Teacher(first, last, age, gender, interests, subject) {
Person.call(this, first, last, age, gender, interests);
this.subject = subject;
}
Teacher.prototype.greeting = () => {
let 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}.`);
};
Teacher.prototype = Object.create(Person.prototype);
Object.defineProperty(Teacher.prototype, 'constructor', {
value: Teacher,
enumerable: false, // so that it does not appear in 'for in' loop
writable: true,
});
const teacher1 = new Teacher('Dave', 'Griffiths', 31, 'male', ['football', 'cookery'], 'mathematics');
for(var key in teacher1){
if(teacher1.hasOwnProperty(key)){
console.log(key);
}
}
// Output: name, age, gender, interests, weight, height, subject
// weight and height should not be here