GREAT question. in javascript, this
is a keyword, and a very tricky one.
Within our object, we have a “private variable space”, usually called a “local scope”. That means that any variables inside that space are completely private, and unavailable to the outside world. We also have, within our object, properties. So we can do things like:
class Person{
constructor(firstName, lastName, age, friends){
/****
* Now, in here, we have created some local variables, which were passed in as parameters.
* firstName, lastName, age and friends are all contained by the object, and not visible to
* anything outside this object. They are local, and they are, to all intents and purposes,
* private.
****/
console.log(`Hello, my name is ${firstName} ${lastName}. Nice ta meetcha!`;
}
}
// what would happen if we did this?
const bobDylan = new Person('Bob', 'Dylan', 74, ['Neil Young','Cass Elliot','Janis Joplin']);
console.log(/** how can I retrieve Bob Dylan's age here? **/)
Suppose, however, we wanted someone to be able to get at the name from the outside? For example, suppose we used the name as a key, to allow us to search for this particular instance of Person? How can we attach one of these variables so they’re visible from outside?
In other words, suppose we wanted to do something like those last two lines, where we get properties like bobDylan.age
?
That’s where the this
keyword comes in. Within the object, this
refers to the object itself, so we can assign properties to it directly, without knowing which instance of our class it is - it is always this
(think of a “you are here” arrow that always follows you around… cos you are here.)
So that means, in our constructor, I could:
class Person{
constructor(firstName, lastName, age, friends){
// Same as before, but let's use the 'this' keyword to attach the variables as attributes.
this.name = {
first: firstName,
last: lastName
}; // note that we aren't restricted to the same variable names - we can juggle it however we want
this.age = age; // or, if we want, simply assign it as-is
}
}
I have to admit, though, I’m curious if we could simply keep them as variables, and use getters and setters to retrieve them - thus keeping the data private, and restricting access to a true interface. Gonna have to play, when I have a result I’ll post the repl here.
EDIT: played a little, and without some funky acrobatics, variables defined within the constructor (whether as parameters or as actual declared variables) are not accessible outside of the constructor. You could do this with ‘traditional’ object notation, but it also can get very convoluted.
The simpler solution is to attach the variables to the object (using the this
keyword) as properties, and use the properties in your class methods.