Proxy and Reflect in Javascript | Part 2

Proxy and Reflect in Javascript | Part 2

·

2 min read

In the previous post, we discussed Proxy in detail. In this post, we will build upon that knowledge and learn some more.

Reflect helps in the creation of Proxy and somewhat allows us to play with internal methods [[Get]] and [[Set]]. Below are some reflect methods:

Let us look at a code example:

let user = {};

Relect.set(user, 'name', 'Aniket Jha'); // [[Set]]

console.log(user.name); // Aniket Jha

Reflect allow us to call operators as functions also there is a reflect method for any proxy traps having the same name and arguments.

let user = {};

user = new Proxy(user, {
  get(target, prop, receiver) {
    console.log(`GET Trap > Target: ${target} Prop ${prop} Receiver ${receiver}`);
    return Reflect.get(target, prop, receiver);
  },
  set(target, prop, value, receiver) {
    console.log(`SET Trap > Target ${traget} Prop ${prop} Value ${value} Receiver ${receiver}`);
    return Relect.set(target, prop, value, receiver);
  },
});

The Reflect methods work nicely with proxy to ensure that traps output and what we expected is the same. Following is an example:

let user = {
  _name: 'User',
  get name() {
    return this._name;
  }
};
let proxyUserObj = new Proxy(user, {
  get(target, prop) {
    return target[prop]; // Note we didn't used reflect here.
  },
});
let admin = {
  __proto__: proxyUserObj,
  _name: 'Admin'
};
console.log(admin.name); // Admin or User 🤔 
// admin.name ?
// `name` is not found on admin obj
// so it will go up in prototype chain
// Note prototype chain is proxyfied object `proxyUserObj`
// it finds `name` property(getter property) on `proxyUserObj`
// resolving for name property trigger proxy `get trap`
// the arguments that are passed to proxy get trap
// target => user
// prop => 'name'
// as trap return traget[prop] i.e user['name'] so `this === user`
// and returned value is `User` 😱 which was not expected
// to prevent it from happening `receiver` argument is requried
// and we can leave it to `Reflect.get(target, props, receiver)` to
// correctly resolve properties for us.

We saw an example of how Reflect is useful for dealing with this Proxy gotcha. I always writereturn Reflect.get(…arguments); 😎. Reflect is awesome to enhance proxy and use it correctly. More on proxy on MDN.

Did you find this article valuable?

Support Aniket Jha by becoming a sponsor. Any amount is appreciated!