JavaScript - this, Reflect & Proxy

Overview

Estimated time: 40–50 minutes

Understand how this is determined, when it’s lexical (arrows), and how to intercept operations using Proxy. Use Reflect to perform default operations in traps and to work with metadata-like operations.

Learning Objectives

  • Predict this in method calls, detached functions, and with call/apply/bind.
  • Use Reflect for standardized operations.
  • Create Proxy for logging, validation, or virtualization.

Prerequisites

this binding

const obj = {
  x: 1,
  getX(){ return this.x; }
};
const m = obj.getX;
m();                 // undefined in strict mode (no receiver)
obj.getX();          // 1 (method call sets this)

const bound = obj.getX.bind(obj);
bound();             // 1

Lexical this (arrows)

const timer = {
  ticks: 0,
  start(){
    setInterval(() => { this.ticks++; }, 1000); // 'this' is timer
  }
};

Reflect

const target = { name: 'Ada' };
Reflect.set(target, 'role', 'admin');
Reflect.get(target, 'name');              // 'Ada'
Reflect.has(target, 'name');              // true

Proxy

const logProxy = (obj) => new Proxy(obj, {
  get(t, k, r){
    console.log('get', String(k));
    return Reflect.get(t, k, r);
  },
  set(t, k, v, r){
    console.log('set', String(k), v);
    return Reflect.set(t, k, v, r);
  }
});

const p = logProxy({ x: 1 });
p.x;      // logs get
p.x = 42; // logs set

Common Pitfalls

  • Forgetting to forward to Reflect.* in traps can break default semantics.
  • Proxies may not be fully transparent for built-ins expecting real instances.