Course contentsShow
← JavaScript
Lesson 759 of 2,72318. ClassesFree lesson

Instance Properties in Constructors

Declaring and initializing instance properties using 'this' within the constructor method.

Instance Properties in Constructors

You'll learn how to declare and initialize instance properties using this within the constructor method.

The Core Idea

When you create a new instance of a class, each object needs its own set of properties with unique values. The constructor method is where you declare and initialize these instance properties by attaching them to this. Each property you assign to this becomes part of that specific object.

Think of it like filling out a form: the constructor is the moment when you write down specific information for each new person—name, age, email—and that data belongs to that person alone, not shared with everyone else.

How It Works

Inside the constructor, you use this.propertyName = value to create properties on the instance being constructed. When you call new ClassName(), JavaScript creates a new object and binds it to this inside the constructor.

class Person {
  constructor(name, age) {
    // These are instance properties
    this.name = name;
    this.age = age;
    this.isActive = true; // Can also set default values
  }
}

const alice = new Person('Alice', 30);
const bob = new Person('Bob', 25);

console.log(alice.name); // 'Alice'
console.log(bob.name);   // 'Bob'
console.log(alice.age);  // 30
console.log(bob.isActive); // true

Each instance (alice and bob) has its own name, age, and isActive properties. Changing alice.name won't affect bob.name because they're separate objects with separate property values.

Key Takeaway: Use this.propertyName = value inside the constructor to create instance properties that belong uniquely to each object created from your class.