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
var taco = { 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;var person =newPerson('Bob');var student =newStudent('Tom','WDI');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:
object instanceof Class
Example 1:
var color1 = {};color1 instanceofObject; // 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;var p =newPerson('Bob');var s =newStudent('Tom','WDI');s instanceofPerson//returns truep instanceofStudent//returns falsePerson instanceofObject//returns trueString instanceofObject//returns trueObject instanceofBoolean//returns false
isPrototypeOf
This method is used a bit less frequently, but the syntax looks like this:
Object.prototype.isPrototypeOf(objectInstance);
Example:
var p =newPerson('Bob');var s =newStudent('Tom','WDI');Person.prototype.isPrototypeOf(s); // returns trueStudent.prototype.isPrototypeOf(p); // returns false
You can read more about the difference between isPrototypeOf and isInstanceOf here