So far, you’ve written the desk’s formatter using method shorthand. Arrows are the shortest way to write a function in JavaScript and the form you’ve used most, so it’s tempting to tidy the formatter into format: (pence) => .... But the function form you pick decides where this comes from. In this lesson, you’ll see what an arrow property on the desk receives and when an arrow is the right choice after all.
Check What an Arrow Property Receives
The Python script keeps the desk as a class, and its formatter gets the desk through self:
class Desk:
currency = "GBP"
def format(self, pence):
return f"{self.currency} {pence / 100:.2f}"
In Python, looking up desk.format fills in self for any function stored on the class, even a lambda. That Python rule doesn’t determine what a JavaScript function receives as this.
Before you trust the tidy version, strip the arrow down until all it does is return this. As a reminder, an arrow without braces, such as () => this, returns the value of its expression. Read this version before you run anything:
const desk = {
currency: "GBP",
format: () => this,
};
console.log(desk.format());
Run this version in the project’s translation-desk/ folder, where package.json makes every .js file a module, or in a .mjs file: