DEV Community

piyush
piyush

Posted on

“THIS” in Javascript.

Prerequisites:

  1. Function declaration, expression, and arrow function
  2. Objects

What exactly is “this” keyword?
The execution context contains three components: variable environment, scope chain and this.

this is a special variable, that takes the value of the owner of the function, and is created for every function [execution context].

The value of the keyword is only assigned only when the function is called, and also the value depends on how the function is called and is not static.

If we simply console.log(this). It will return the global object.

this keyword doesn't NOT point to the function itself, or the variable environment.

We will look at the ways functions are called and the value the keyword takes:

1. Method call:

If a function is called through this method, the this keyword will point to the object in which it is called for example:

//code 
const student={
    name:"Piyush",
    logThis:function(){
        console.log(this)
    }
}


console.log(student.logThis())


// Output: this point to the object where it is called


name: 'Piyush', print: ƒ}
Enter fullscreen mode Exit fullscreen mode

2. Simple function call

There are two different values this might point to, it depends on whether the strict mode is enabled or not.

a. If strict mode is enabled:

It returns undefined.

//code 
`use strict`
function print12() {
    console.log(this)
}
console.log(print12())

// output
undefined

Enter fullscreen mode Exit fullscreen mode

b. Without strict mode

It returns the global object.

//code 

function print12() {
    console.log(this)
}

console.log(print12())


// output: window object
Window {window: Window, self: Window, document: document, name: '', location: Location, …}
Enter fullscreen mode Exit fullscreen mode

3. Arrow function :

Arrow functions do not get their own “this” keyword. Using this keyword inside the arrow function will simply point to the surrounding function. It is also called the “lexical this” keyword.

//code
const student={
    name:"Piyush",
    age:20,
    print12:()=> {
        console.log(this)
    }
}
console.log(student.print12())


//output: window object
Window {window: Window, self: Window, document: document, name: '', location: Location, …}

Enter fullscreen mode Exit fullscreen mode

Here, “this” does not point to this object where the function is called, but points to the surrounding function, here the global (object).

5. Method borrowing and this keyword :

Say we have two objects student1 and student2. Student1 has “printage” method and we copy it to student2.

//code
const student1={
    name:"Piyush",
    age:20,
    printage:function() {
        console.log(this)
        console.log("Your birth year", 2022-this.age)
    }
}


const student2={
    name:"ABC",
    age:18,
}


//copying student1.printage method to student2
student2.printage=student1.printage
console.log(student2.printage())


//output
{name: 'ABC', age: 18, printage: ƒ}
Your birth year 2004
Enter fullscreen mode Exit fullscreen mode

When this line is executed “printage” method even though it is in student1, “this” points to the object that is calling the method, here student2 is invoking the method so we get the above output.

6. Call, apply and bind method:

We can explicitly set up the value of “this” using these methods.

a. Call

The first argument in the call method should always be the object we want the “this” keyword to point to.
Here we have two students: student1 and student2.

We copy “printage” method from student1 and store it in birthyear. birthyear is a regular function.

After that we use birthyear.call method, the first argument student2 is the object we want this to reference. After that, we can pass the required arguments for the function.

Example :

const student1={
    name:"Piyush",
    age:40,
    printage(score) {
        console.log(this)
        console.log("Hi "+this.name+". You scored "+score)
    }
}


const student2={
    name:"ABC",
    age:18,
}


// copy print age
const birthyear=student1.printage


// call method
birthyear.call(student2,20)


//output
{name: 'ABC', age: 18}
Hi ABC. You scored 20
Enter fullscreen mode Exit fullscreen mode

So we get, the output: {Hi ABC. You scored 20}

b. Apply:

The apply method is similar to the call method. The only difference here is that while calling the apply method the arguments of the function are passed in an array.
Example:

//code
const student1={
    name:"Piyush",
    age:30,
    printage(score) {
        console.log(this)
        console.log("Hi "+this.name+". You scored "+score)
    }
}


const student2={
    name:"ABC",
    age:18,
}


// copy print age
const birthyear=student1.printage


// apply method
birthyear.apply(student2,[20])


//output
{name: 'ABC', age: 18}
Hi ABC. You scored 20


Enter fullscreen mode Exit fullscreen mode

c. bind :

The bind method is a bit different from the call and apply method. It takes in one argument, i.e the object for this, and returns a new function. Now we can use the function to pass arguments.
Example :

//code
const student1={
    name:"Piyush",
    age:20,
    printage(score) {
        console.log(this)
        console.log("Hi "+this.name+". You scored "+score)
    }
}


const student2={
    name:"ABC",
    age:18,
}

// the bind method will return a function, while this will point to student2
const birthyear=student1.printage.bind(student2)


//use the function to pass arguments
birthyear(39)


//output
{name: 'ABC', age: 18}
Hi ABC. You scored 39
Enter fullscreen mode Exit fullscreen mode

Top comments (0)