JavaScript – Let’s Change This

There are times that we need to change the context of the ‘this’ keyword. since functions are objects and they have properties, we can set them and access them. with ‘call’, ‘apply’ and ‘bind’ we can change the ‘this’ keyword, and we can change the context in which the function is invoked.

The call and apply methods are doing the same as when we invoke a function:


function greetingHello() {
  console.log('Hello')
}

greetingHello.call();  // Hello.


function greetingHi() {
  console.log('Hi');  // Hi.
}

greetingHi.apply();

We can even pass parameters to the function with these 2 methods, but with a small difference. with ‘call’ we pass a set of parameters and with ‘apply’ we pass an array of parameters:


function greetingHello(firstName, lastName) {
  console.log('Hello' + ' ' +  firstName + ' ' +  lastName);
}

greetingHello.call(null, 'Nisan', 'Sabag');


function greetingHi(firstName, lastName) {
  console.log('Hi' + ' ' +  firstName + ' ' +  lastName);
}

greetingHi.apply(null, ['Nisan', 'Sabag']);

Notice that the first value we pass to this method is null since we do not change the context of this and in this example, we don’t need to, since we are not using the ‘this’ keyword in the functions “greetingHello” and “greetingHi”.

When we want to change the context of this, instead of passing null we will pass the object to which we want the ‘this’ keyword to refer to. let’s see an example:


const person1 = {
  name: 'Lisa',
  coins: 50,
  addCoin: function() {
    return ++this.coins;
  }
}

const person2 = {
  name: 'Bart',
  coins: 30
}

person1.addCoin.call(person2); //31
person1.addCoin.call(person2); //32

In the example above we are borrowing the method from object person1 and using it on person2.

The bind method is a bit different. instead of calling the function, it returns a function:


const person1 = {
  name: 'Lisa',
  coins: 50,
  addCoin: function() {
    return ++this.coins;
  }
}

const person2 = {
  name: 'Bart',
  coins: 30
}

const addCointToPerson2 = person1.addCoin.bind(person2);
addCointToPerson2(); //31
addCointToPerson2(); //32

There is a useful trick that we can do with the “bind” method and it’s called “function currying”. there is no connection between this example to the ‘this’ keyword but it is nice to know:


function multiply(a,b) {
  return a*b;
}

let multiplyByTwo = multiply.bind(this, 2);
console.log(multiplyByTwo(3));  // 6
console.log(multiplyByTwo(6));  // 12

We created a new function that will multiply any given number by two.