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."
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."
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)
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
it's pretty easy to accidentally miss that only
name
andsendName
use the dog's name. bothfullName
andsayName
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.
I would avoid
this
keyword, because it is easy mess up thingsinstead you can, for example, use closures:
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.