Typescript Classes 10 exercises

Using `this` in Functions and Objects

In addition to using this in classes, you can also use it in functions and objects.

Consider this calculator. It has two methods, similar to a class: setValues, and add.

The setValues method takes in an x number and a y number and assigns them to the object. The add method adds up

Loading exercise


00:00 We've been talking a lot about classes and using this inside classes, but you can also use this in functions and objects too. Let's say that we have a calculator object here. This calculator object has a couple of methods on it. It has set values and it has add, just

00:16 like classes. And this add function adds up this dot X and this dot Y and returns it. Set values, kind of like the move function that we had before, takes in an X number and a Y number and sets them to the class. And you can see that a couple of things are happening.

00:33 First of all, the tests are actually failing. So it's actually failing to add together like 1 and 2 here inside set values. That's interesting. And also we're getting these errors here. First of all, this implicitly has type any because it does not have a type annotation.

00:48 Your job is to figure out why these errors are occurring, fix them, and to kind of like figure out also how to type this as well inside these functions. There's something suspicious about this set values function, but I'll leave that as an exercise to the reader. The code

01:04 you can change is just within here. Don't change any of the code here and good luck.