Accessing Instance Properties in Methods
What you'll learn: How to use this inside instance methods to read and modify an object's own properties.
When you define instance methods in a class, those methods need a way to access the specific object they're working with. That's where this comes in — it refers to the instance that called the method.
Why this Matters in Methods
Think of this as "the current object." When you call person.greet(), inside the greet method, this refers to person. This allows your method to access that object's properties using this.propertyName.
Without this, your methods would have no way to know which object's data to work with.
Reading Properties with this
Inside a method, use this.propertyName to read an instance property:
class Person {
constructor(name, age) {
this.name = name;
this.age = age;
}
greet() {
return `Hello, I'm ${this.name} and I'm ${this.age} years old.`;
}
}
const alice = new Person('Alice', 30);
console.log(alice.greet()); // "Hello, I'm Alice and I'm 30 years old."
Modifying Properties with this
You can also change instance properties from within methods:
class Counter {
constructor() {
this.count = 0;
}
increment() {
this.count = this.count + 1;
}
getCount() {
return this.count;
}
}
const counter = new Counter();
counter.increment();
console.log(counter.getCount()); // 1
Key Takeaway: Use this.propertyName inside instance methods to access and modify the properties of the specific object that called the method — this is your bridge between a method and its object's data.