Call, Apply, and other Functions

call

Call and apply are two functions that allow us to change what this represents. This is why this can be difficult to deal with in JavaScript.

Example 1:

const getAge = function(friend) {
  return friend.age;
};

const john = { name: 'John', age: 21 };
getAge(john);

rewritten using call

const getAge = function() {
  return this.age;
};

const john = { name: 'John', age: 21 };
getAge.call(john);

Example 2:

const setAge = function(friend, newAge) {
  friend.age = newAge;
};

const john = { name: 'John', age: 21 };
setAge(john, 35);

rewritten using call

apply

apply works just like call, but your second parameter is an array of objects instead of a comma separated list.

Going back to Example 2, here's what it would look like with apply.

Calling on a solution

Let's talk about using call or apply to set the this context for a function before it is run.

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.

Still confused? Understanding this once and for all

Useful methods when working with inheritance

hasOwnProperty

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

Example 2 with inheritance

instanceof

This method is a bit more common, and the syntax looks like this:

object instanceof Class

Example 1:

Example 2 with inheritance

isPrototypeOf

This method is used a bit less frequently, but the syntax looks like this:

Example:

You can read more about the difference between isPrototypeOf and isInstanceOf here

Last updated

Was this helpful?