Skip to content

Simple explanation of "this" and "Function.prototype.call" in JavaScript

Daisho Komiyama edited this page Jul 31, 2020 · 2 revisions

this

The this keyword lets you refer to an object from within that object.

Example:

function add(x) {
  return this + x;
}

Number.prototype.add = add;

(10).add(4); // 14

Function.prototype.call

Function.prototype.call quite simply lets this point to given context when you invoke a function. Calling the .call() method on a function, will immediately invoke that function.

Example:

const cat = {
    sound: "meow",
    say: function() {
        return this.sound;
    }
};

const dog = {
    sound: "bow"
};

cat.say(); // "meow"
dog.say(); // TypeError: dog.say is not a function

cat.say.call(dog); // "bow" YES!
Clone this wiki locally