Let's talk about using call or apply to set the this context for a function before it is run.
function Person(name) {
this.name = name;
this.friends = [];
}
Person.prototype.addFriend = function(name) {
this.friends.push(new Person(name));
};
function Student(name, course) {
// masks all the constructor properties including name (as the second parameter)
Person.call(this, name);
this.course = course;
// If we wanted to, we could also use .apply like so:
// Person.apply(this, [name]);
}
Student.prototype = Object.create(Person.prototype);
Student.prototype.constructor = Student;
The code above is why we forgo talking about this until now. In the context of event listener callbacks, this refers to the DOM element that trigged the event. But here, this can really be anything you want it to be.
Object.hasOwnProperty('nameOfProperty') - always make sure the name of the property is in quotes. Classes that inherit from other classes will also return true if the property is checked.
function Person(name) {
this.name = name
}
Person.prototype.greet = function() {
return 'Hello, my name is ' + this.name;
};
function Student(name, course) {
Person.call(this, name);
this.course = course;
}
Student.prototype = Object.create(Person.prototype);
Student.prototype.constructor = Student;
const p = new Person('Bob');
const s = new Student('Tom', 'SEI');
s instanceof Person //returns true
p instanceof Student //returns false
Person instanceof Object //returns true
String instanceof Object //returns true
Object instanceof Boolean //returns false
isPrototypeOf
This method is used a bit less frequently, but the syntax looks like this:
Object.prototype.isPrototypeOf(objectInstance);
Example:
const p = new Person('Bob');
const s = new Student('Tom', 'WDI');
Person.prototype.isPrototypeOf(s); // returns true
Student.prototype.isPrototypeOf(p); // returns false
You can read more about the difference between isPrototypeOf and isInstanceOf here