this
keyword in JavaScript represents the execution context of a function.const user = { name: 'Siva', greet: function() { return `Hi, ${this.name}`; } } console.log(user.greet()); // Hi, Siva
user
where it is defined. Using this we can access all the properties declared as part of user object.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(thisArg, arg1, arg2, ....);
function greet(greeting, punctuation) { console.log(`${greeting}, ${this.name} ${punctuation}`) } const person = { name: 'Siva', } greet.call(person, 'Hello', '!'); //Hello, Siva!
.apply(thisArg, [arg1, arg2, ...]);
function greet(greeting, punctuation) { console.log(`${greeting}, ${this.name} ${punctuation}`) } const person = { name: 'Siva', } greet.apply(person, ['Hello', '!']); //Hello, Siva!
function greet(greeting, punctuation) { console.log(`${greeting}, ${this.name} ${punctuation}`) } const person = { name: 'Siva', } const newGreet = greet.bind(person, 'Hello', '!'); newGreet(); // Hello, Siva!