Let's talk about using call or apply to set the this context for a function before it is run.
functionPerson(name) {this.name = name;this.friends = [];}Person.prototype.addFriend=function(name) {this.friends.push(newPerson(name));};functionStudent(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.
Example 1
consttaco= { food:'taco'}taco.hasOwnProperty(food); // returns an errortaco.hasOwnProperty('food'); // returns true
Example 2 with inheritance
functionPerson(name) {this.name = name}Person.prototype.greet=function() {return'Hello, my name is '+this.name;};functionStudent(name, course) {Person.call(this, name);this.course = course;}Student.prototype=Object.create(Person.prototype);Student.prototype.constructor= Student;constperson=newPerson('Bob');conststudent=newStudent('Tom','SEI');person.hasOwnProperty('name'); //returns truestudent.hasOwnProperty('course'); //returns truestudent.hasOwnProperty('name'); //returns true
instanceof
This method is a bit more common, and the syntax looks like this: