this
`this` is the object the code of a class or method is working on: the current instance.
Inside a class constructor or method, this points to the specific instance. So this.owner = owner stores the value on the object being created with new.
Each instance has its own data, and this is how you reach it. If two accounts have different owner values, the same method returns each one's own.
The value of this depends on how the function is called, not where it was written. With account.greet() it is account. If you pull the method into a variable and call it alone, this is lost. An arrow function, however, uses the this of the place where it was created.
The course shows it from lesson 01.07: this.owner = owner; // this = the object being built. this is plain JavaScript and works the same when Node runs the code.
Reach for it when: a constructor or method needs to read or store data on the current instance.
Examples
Common mistake
class Greeter {
name = "Ana";
hello(): string {
return "Hi " + this.name;
}
}
const g = new Greeter();
const f = g.hello;
console.log(f());Why: Calling `f()` with no object makes `this` `undefined` inside a class, and reading `this.name` fails.
How to write it: Call the method on its object (g.hello()), use g.hello.bind(g), or define the method as an arrow function in a field.
