DEV Community

Cover image for The "this" keyword in JavaScript
CJ
CJ

Posted on • Updated on

The "this" keyword in JavaScript


Let's understand this by mimicking a real-world example.

In the real world

  • We have things, objects, entities, etc (Kid, Car, User)
  • And these things act (Jump, Accelerate, decelerate, buy stuff, login)

In Javascript world

  • Let's assume kid as an Object 🧒
'use strict'
let kid = { Name: 'Rob', Age : 6} 
Enter fullscreen mode Exit fullscreen mode

And to teach this kid to say hello
Give this kid a method (action)

sayHi() 👋

'use strict'

let kid = { Name: 'Rob', Age : 6}

kid.sayHi() = function() {
  return '👋 Hello!'
}

kid.sayHi()  //👋 Hello!
Enter fullscreen mode Exit fullscreen mode

Now change it so that the kid reply with its name also

'use strict'
let kid = { Name: 'Rob', Age : 6}

kid.sayHi() = function() {
  return '👋 Hello, I am ' + Name
}

kid.sayHi()  // this will return an reference error
Enter fullscreen mode Exit fullscreen mode

Which is the same as :

'use strict'
let kid = { 
 Name: 'Rob',
 Age : 6,

 sayHi() {
  return '👋 Hello, I am ' + Name
 }
}
kid.sayHi()  // this will return an reference error
Enter fullscreen mode Exit fullscreen mode

The reason it didn't return Name Rob
is because Name does not have access to the object kid

To solve this we will add this

'use strict'
let kid = { 
 Name: 'Rob',
 Age : 6,

 sayHi() {
  return '👋 Hello, I am ' + this.Name
 }
}
kid.sayHi()  // 👋 Hello, I am Rob
Enter fullscreen mode Exit fullscreen mode

Here the value of Name is taken from the object it is being called i.e., kid

The value of this is evaluated at call-time and does not depend on where the method was declared, but rather on what object is being called from i.e, before the dot.

To further understand this let us create a method outside of the kid object

'use strict'

function myAge() {
  return 'I am ' + this.Age + ' years old'
}

let parent = {
 Name: 'Alex',
 Age : 32
}

let kid = { 
 Name: 'Rob',
 Age : 6,

 sayHi() {
  return '👋 Hello, I am ' + this.Name
 }
}

kid.sayHi()  // 👋 Hello, I am Rob

kid.tellAge = myAge
console.log(kid.tellAge()) // I am 6 years old

parent.tellAge = myAge
console.log(parent.tellAge()) // I am 32 years old


Enter fullscreen mode Exit fullscreen mode

Now let us understand how chaining methods work with an example of a car;🚗

...
There's a car which is stationary and with every acceleration and deceleration, it moves 1 meter forward and backward respectively.

'use strict'

let car = {
  distanceTraveled: 0,

  accelerate() {
    this.distanceTraveled++
  },

  declerate() {
    this.distanceTraveled--
  },

  showDistance: function() { 
    // shows the current distance traveled
    console.log( this.distanceTraveled )
  }
}

car.accelerate().declerate().accelerate().showDistance() 
// this will return an error "Cannot read property declerate' of undefined"
Enter fullscreen mode Exit fullscreen mode

Remember the value of this is evaluated during run-time, so
after the first acceleration, distanceTraveled value becomes 1 but when the code calls the next method decelerate it does not get the object car due to which it returns typeError ❌

To fix this, we just have to return the object after calling a method like this:

'use strict'

let car = {
  distanceTraveled: 0,

  accelerate() {
    this.distanceTraveled++
    return this
  },

  declerate() {
    this.distanceTraveled--
    return this
  },

  showDistance: function() { 
    // shows the current distance traveled
    console.log( this.distanceTraveled )
  }
}

car.accelerate().declerate().accelerate().accelerate().showDistance() // 2
Enter fullscreen mode Exit fullscreen mode

I hope this article was helpful.
Feel free to give a suggestion or shoot me a message on Twitter or LinkedIn.
See you in the next post!👋

Top comments (0)