DEV Community

Cover image for Reusable Code with "this" Keyword
Todd Carlson
Todd Carlson

Posted on

Reusable Code with "this" Keyword

If you are familiar with JavaScript objects, you know that you can access the value of an object property using dot notation like this:

let dog = {
    name: "Doug",
    breed: "pug",
    sayName: function() {return "The name of this dog is " + 
    dog.name + "."}
}
console.log(dog.sayName())
// "The name of this dog is Doug."
Enter fullscreen mode Exit fullscreen mode

This is a fine way to access a property, but, if we want to future proof our code and account for the fact that variable names sometimes change, this is not the best way to access object properties. If we were to change the variable name from "dog" to "animal," any other code that references the original variable name of "dog" would need to be updated to the new variable name of "animal." You could see how this could quickly escalate if the original variable is referenced in a lot of other places.

However, this problem can be easily avoided if we were to use the "this" keyword. The "this" keyword is a very deep topic that is beyond the scope of this short blog post. I am merely showing you one way to use it. However, "this" is something that I implore all of you to look deeper into.

In its present context, "this" refers to the object that is associated with it, which, in this case, is "dog." We can access the same name property, only this time we use the "this" keyword instead of the "dog" variable:

let dog = {
    name: "Doug",
    breed: "pug",
    sayName: function() {return "The name of this dog is " + 
    this.name + "."}
}
console.log(dog.sayName())
// "The name of this dog is Doug."
Enter fullscreen mode Exit fullscreen mode

We achieve the same result as before, only now if we were to change the variable name to "animal" we would not have to find and modify all of the references to "dog" in our code. Our code is now reusable and easier to read.

Top comments (3)

Collapse
 
willsmart profile image
willsmart • Edited

This kind of encapsulation is a great idea, but I strongly suggest getting an IDE setup that can tell you what type this has at the time you use it. I think it's one of the best reasons to use Typescript.

For example, in

function foo() {
  this.name = 'bob';
  const dog = {
    name: 'fluffy',
    fullName: `sir ${this.name}`,
    sayName: () => { spawn('say', [this.name]) },
    sendName: function() { send(this.name) }
  }
}
Enter fullscreen mode Exit fullscreen mode

it's pretty easy to accidentally miss that only name and sendName use the dog's name. both fullName and sayName will use "bob"

As you say, the reasons for this are a little out of scope, but getting a good IDE setup will catch this bug just as well as knowing why it happens, and is a must if you're going to use this in JS imo.

VSCode with Typescript (or just a good JS type inference setup) will put nice big red squigglies under the dodgy bits.

Collapse
 
stereobooster profile image
stereobooster

I would avoid this keyword, because it is easy mess up things

let dog = {
    name: "Doug",
    breed: "pug",
    sayName: function() {return "The name of this dog is " + 
    this.name + "."}
}
let sayName = dog.sayName
sayName()
// "The name of this dog is 0.8151551794824166."
// To make it work you need
sayName.call(dog)
// or 
sayName.apply(dog)
Enter fullscreen mode Exit fullscreen mode

instead you can, for example, use closures:

const createDog = () => {
  const self = {
    name: "Doug",
    breed: "pug",
    sayName: () => `The name of this dog is ${self.name}.`
  }
  return self
}
Enter fullscreen mode Exit fullscreen mode
Collapse
 
eelstork profile image
Tea

I'm not sure Todd. You now have "this" all around your codebase. You replace dog with animal that is something a search and replace will handle for you. But now you want to review occurrences of "animal" how do you search for that once it has come to "this".

It's a good idea and may work in some cases but could also be a case of "better is worse than good", if that even makes sense.