Chapter XXI · The `this` Keyword

Constructor

When a function is invoked with the `new` keyword, `this` binds to the newly created blank object instance.

01 How It Works

Think of stamping a new custom label badge onto a freshly minted product unit.

Constructor invocation creates a fresh object and automatically assigns it as the `this` binding context during execution.

example.js
function Person(name) {
  this.name = name; // 'this' points to new instance
}
const p = new Person("Charlie");
  1. 1. Invoke a constructor function using `new`.

  2. 2. Engine assigns a new object instance to `this`.

  3. 3. Properties are attached to the new instance.

02 Practical Example

Here is how you might see this concept applied in real-world code:

practical.js
function Point(x, y) {
  this.x = x;
  this.y = y;
}
const pt = new Point(10, 20);

Key Takeaway

Constructor calls bind `this` to the newly instantiated object.

Related Concepts