This & Bind Functions

📚 Table of Contents

This

Example

const user = { name: 'Siva', greet: function() { return `Hi, ${this.name}`; } } console.log(user.greet()); // Hi, Siva

Call, Apply & Bind

These are the key tools for controlling this in javascript, that is with these functions you can tell the javascript where to refer when 'this' is used.

.call()

.call(thisArg, arg1, arg2, ....);

Example

function greet(greeting, punctuation) { console.log(`${greeting}, ${this.name} ${punctuation}`) } const person = { name: 'Siva', } greet.call(person, 'Hello', '!'); //Hello, Siva!

.apply()

.apply(thisArg, [arg1, arg2, ...]);

Example

function greet(greeting, punctuation) { console.log(`${greeting}, ${this.name} ${punctuation}`) } const person = { name: 'Siva', } greet.apply(person, ['Hello', '!']); //Hello, Siva!

.bind()

Example

function greet(greeting, punctuation) { console.log(`${greeting}, ${this.name} ${punctuation}`) } const person = { name: 'Siva', } const newGreet = greet.bind(person, 'Hello', '!'); newGreet(); // Hello, Siva!