1

Good morning everyone,

I'm an enthusiastic ES6 amateur and I've recently approached the "Proxy object" subject for the first time. From the online material I've came across so far my understanding is that a Proxy is acting as a wrapper, on a generic object, that intercept actions on it in order to change its behavior. With this in mind I've tried to run the following snippet and the outcome is surprising (at least for me):

 "use strict";
 
  let user = {
    id: {
      name: "Johnny",
      surname: "Potts",
    },

    age: 44,
  };

  let userProxy = new Proxy(user, {
    get(target, key, receiver) {
      alert("GET triggered");
      return Reflect.get(...arguments);
    },

    set(target, key, value, receiver) {
      alert("SET triggered");
      return Reflect.set(...arguments);
    },
  });

  userProxy.id.name = "Pete"; //change an existing property in the nested object.

  userProxy.id.gender = "male"; //introduce a new property in the nested object.

As you'll easily notice by running this code, the "GET" trap triggers every time instead of "SET" and the new property doesn't get written inside the "user" object however the existing one gets updated.

Can anyone explain me why? Thanks in advance for your time and support.

1 Answer 1

0

The answer is that PROXY only replace the "direct" object. Any other object linked to the proxied object, such as the nested one in this case, is not trapped. That explains also why "GET" is always invoked; nested object needs to be retrived first from parent one...'Elementary, my dear Watson!'

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.