DEV Community

Randy Rivera
Randy Rivera

Posted on

Making Code More Reusable with the this Keyword

  • The last post introduced a method to the dog object. It used dog.name dot notation to access the value for the name property within the return statement:
sayName: function() {return "The name of this dog is " + dog.name + ".";}
Enter fullscreen mode Exit fullscreen mode
  • While this is a valid way to access the object's property, there is a pitfall here. If the variable name changes, any code referencing the original name would need to be updated as well. In a short object definition, it isn't a problem, but if an object has many references to its properties there is a greater chance for error.

  • A way to avoid these issues is with the this keyword:

let dog = {
  name: "Anakin",
  numLegs: 4,
  sayName: function() {return "The name of this dog is " + this.name + ".";}
};

dog.sayLegs();
Enter fullscreen mode Exit fullscreen mode
  • this is a deep topic, and the above example is only one way to use it. In the current context, this refers to the object that the method is associated with: dog. If the object's name is changed to husky, it is not necessary to find all the references to dog in the code. It makes the code reusable and easier to read.

Top comments (0)