Can you explain the .apply() method in a simple manner?

I’ve tried going through quite a few articles explaining the .apply() method and have even tried watching some YT videos explaining it. What confuses me the most is when “this” is used, since I don’t have much experience using it

I’m reading this question more as not knowing what the this keyword means/does, rather than the apply method itself, but let me know if I’m totally off.

the this keyword refers to some object. The particular object it refers to depends on the context or how the keyword this is bound. There are 4 possibilities:

  1. default binding - this refers to the window in the global context, unless you are using strict mode, and then it is undefined
  2. implicit binding - this is inside of an object that you have declared. example below would produce “hejmaria says hello!” if we invoked sayHello with person.sayHello();
var hejmaria = {
    username: "hejmaria",
    sayHello: function(){
        return this.username + " says hello!";
    }
};
  1. explicit binding - this is determined when we set it explicitly using call, apply, or bind. More details after this numbered list.
  2. new keyword - this is referred to an object which is created from a (constructor) function after the new keyword.

With explicit binding, call and apply will immediately invoke the function it is called to. The difference between call and apply is that you can pass in multiple arguments into call (this argument and then whatever other arguments you want, versus passing in a just two arguments with the this argument and an array with apply. Example:

var hejmaria = {
    username: "hejmaria",
    sayHello: function(){
        return this.username + " says hello!";
    },
    add: function (a, b){
        return this.username + " added " + (a + b);
    }
};

var vlai = {
	username: "v-lai",
};

hejmaria.add(1,3) // "hejmaria added 4"
hejmaria.add.call(vlai, 1, 4) // "v-lai added 5"
hejmaria.add.apply(vlai, [1, 5]) // "v-lai added 6"

bind is just like call, but the function is not immediately invoked.

var vpartial = hejmaria.add.bind(vlai, 1) // undefined
vpartial(7) // "v-lai added 8"

Hope this helps.

1 Like