If you already have a subscription, you can sign in.
Enjoy free content straight from your inbox 💌
00:00
Here we have a simple JavaScript class called person that takes an initial value for the age property and then provides two methods. One, grow old, which increments the age property, and then a method called age, which returns the current age of the person. And we create an instance of the person with an initial age of zero call the grow old method to increment the age to one and then log out the age. And of course, if you run this code, we expect to log out the age of one. There are two ways to think about this
00:32
keyword in JavaScript. One way is the calling context. The other way is scoped other than arrow and bound functions. This is driven by the calling context. Since the grow old method is not an arrow function, this will be driven by the calling context. So when we are invoking grow old on the person object, this will be person. Now, as we have discussed before, functions in JavaScript are first class, and what this means is that they can be stored in a variable. So we can store the grow old method into a variable
01:05
and then invoke it directly. Now in this case, since the method is not being invoked on any object, the calling context and therefore the key key word, this will be undefined within the function body. And if you run this code, you can see that error shows up on the console. Now you might be tempted to think that you would never store a method in a variable and never end up with this code In real world, however, this method to variable assignment can occur quite easily. For example, if you give this method to set time out to invoke later, this will be lost.
01:38
As far as the invocation within set, time out is concerned. It'll be the same as just calling the grow old method by itself. Fortunately, JavaScript also offers a ally scoped this. And the way to use that is with an error function. So instead of creating a simple method, we create grow old as a property pointing to an error function. Error functions in JavaScript. Capture this from the surrounding context. Since all property initializes execute at the end of the constructor, this will be bound to whatever instance is present within the constructor.
02:12
And now since it is no longer driven by the calling context, we don't need to worry about it being invoked incorrectly and both our usages both as a variable and within the set, timeout will work as expected. So if you log out the age after two seconds, you can see that the answer is correct with the value of two.