Explain this keyword in JS with examples

What is the ‘this’ keyword?

// output: Window { …}console.log(this)
let counter = {
count: 0,
show: function () {
return ++this.count;
},
};
counter.show();

Types of Binding in Javascript

1. Default Binding

var name = 'Javascript';function getName() {
console.log(this.name);
}
getName();/* Output: Javascript */
var name = 'Javascript';function getName() {
'use strict';
console.log(this.name);
}
getName();/* Output: TypeError: `this` is `undefined` */

2. Implicit Binding

// function is defined
function getName() {
console.log(this)
}
const obj = {
count: 4,
getName: getName,
}
// function is called using obj
obj.getName(); // count = 4
function getName() {
console.log(this.count)
}
const obj = {
count: 4,
getName: getName,
nestedObj: {
count: 6,
getName: getName
}
}
obj.nestedObj.getName(); // count = 6

3. Explicit Binding

function alert() { 
console.log(this.count + ' number');
}
const myObj = {
count: 4
}
alert.call(myObj); // 4 number
const person = {
name: "John",
age: 18,
}
function getPerson(params) {
/* output: John is not available today. */
console.log(`${this.name} is ${params[0]} ${params[1]}`)
}
getPerson.apply(person, ["not available", "today"])

4. Constructor Call Binding

  • Creation of a new object.
  • A newly constructed object is linked to the function that constructed it.
  • The constructed object is set as this binding to that function call.
function setCount(age) { 
this.count = count;
}
const num = new setCount(4);
console.log(num.count); // 4

Summary

  • this keyword, when used in a function, binds that function to a context object.
  • There are four types of binding: Default, Implicit, Explicit, and Constructor call (new).
  • The behavior of this keyword changes between strict and non-strict modes.

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Siddharth Rastogi

Siddharth Rastogi

41 Followers

I am a full stack developer, I have an expertise in Web Development. I write tech stuff and share my knowledge with others with the help of articles.