JavaScript objects provide the reader with some special features that make object-based programmer more effective and more efficient. In this article I’m going to describe three of these features — the this
keyword, getters, and setters.
If there was ever a more confusing keyword in computer programming than thethis
keyword, I don’t know what it is. However, the concept behind this
is not really that hard to understand. The keyword this
refers to the current object that is in reference where the code using it is executed.
Examples are often better than explanations, so here is an example. First, let’s write an object constructor function and a short program to test it:
function Person(n, a) {
this.name = n;
this.age = a;
}
let me = new Person("Mike", 63);
print(me.name + ", " + me.age);
The output from this program is:
Mike, 63
The this
keyword is used to reference the current object properties in memory when the code is running. You can translate it as “assign the value in n to the name property of this particular object.”
Another great use of this
is to disambiguate code where the property name is the same as the parameter name, as in this rewrite of the constructor function:
function Person(name, age) {
this.name = name;
this.age = age;
}
You can’t leave the this
keyword out of a constructor definition but it still helps make the code clearer to the reader.
The this
keyword plays an important role in working with objects in JavaScript and I hope I’ve made its use clearer to you.
#javascript-development #learning-javascript #learn-to-code #javascript #learn-to-program