call() - apply() - bind()

In JS the call, apply and bind methods can be used to assigned objects to the 'this' keyword.

Call() method example:

const person = {
    fullName: function () {
        return this.firstName + ' ' + this.lastName
    }
};

const person1 = {
    firstName: 'Rodolfo',
    lastName: 'Jaubert'
};

console.log(person.fullName.call(person1));

Apply() method example:

const obj = { name: 'John' };
let greeting = function (a, b) {
    return `${a} ${this.name}. ${b}`
}

console.log(greeting.call(obj, 'Hello', 'How are you?')); // With call
console.log(greeting.apply(obj, ['Hello', 'What is up?'])); // With apply

Bind() method

const obj = { name: 'John' };

let greeting = function (a, b) {
    return `${a} ${this.name}. ${b}`
}

let bound = greeting.bind(obj);
console.log(bound('Hello', 'Hey!!'));

Last updated