0

i have an interesting example of code that's not working like i'm expected.

I really dont understand why my obj wouldnt proxy. I'm expect that obj ill proxy via link, but it's not. Can anyone explain how it's works and what I don't understand? Thank you!

let obj = {
  foo: "123"
};

function test(fn, object) {
  object = new Proxy(object, {
    get(target, key) {
      console.log('get');
      return target[key];
    },
    set(target, key, value) {
      console.log('set');
      target[key] = value;
      return true;
    }
  });
  fn();
}

test(() => {
  obj.foo = "helloworld";
  console.log(obj.foo);
}, obj);

UPD: i want to assign object to proxy variable ONLY through arguments can i?

2
  • What is object did you mean obj = new Proxy? Commented Feb 2, 2023 at 17:39
  • @Konrad object is the argument to test() Commented Feb 2, 2023 at 17:39

1 Answer 1

1

Either assign the proxy to obj

let obj = {
  foo: "123"
};

function test(fn, object) {
  obj = new Proxy(object, {
    get(target, key) {
      console.log('get');
      return target[key];
    },
    set(target, key, value) {
      console.log('set');
      target[key] = value;
      return true;
    }
  });
  fn();
}

test(() => {
  obj.foo = "helloworld";
  console.log(obj.foo);
}, obj);

Or pass the proxy as an argument

let obj = {
  foo: "123"
};

function test(fn, object) {
  const o = new Proxy(object, {
    get(target, key) {
      console.log('get');
      return target[key];
    },
    set(target, key, value) {
      console.log('set');
      target[key] = value;
      return true;
    }
  });
  fn(o);
}

test((o) => {
  o.foo = "helloworld";
  console.log(o.foo);
}, obj);

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

9 Comments

Thanks for the answer, but I don’t want to do this, can you explain why this happens, because everything is logical in my opinion and the object should become proxied by reference
The first solution modifies obj permanently, I think they only want the proxy to be in effect during the call to test().
@user469485 Creating a proxy doesn't modify the object itself. You have to access the properties through the proxy.
See the examples in MDN -- you have to access proxy2.propertyname
The code in the question doesn't work, because an assignment to a parameter doesn't change the original argument.
|

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.