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?

user469485
  • 55
  • 6

1 Answers1

0

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);
Konrad
  • 21,590
  • 4
  • 28
  • 64
  • 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 – user469485 Feb 02 '23 at 17:43
  • 1
    The first solution modifies `obj` permanently, I think they only want the proxy to be in effect during the call to `test()`. – Barmar Feb 02 '23 at 17:43
  • @user469485 Creating a proxy doesn't modify the object itself. You have to access the properties through the proxy. – Barmar Feb 02 '23 at 17:44
  • See the examples in [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy) -- you have to access `proxy2.propertyname` – Barmar Feb 02 '23 at 17:45
  • The code in the question doesn't work, because an assignment to a parameter doesn't change the original argument. – Konrad Feb 02 '23 at 17:45
  • @Konrad, As far as i know argument in function will assign by link, so why not? – user469485 Feb 02 '23 at 17:46
  • @Barmar, I just want to create a proxied object and assign it by link – user469485 Feb 02 '23 at 17:48
  • https://stackoverflow.com/questions/21978392/modify-a-variable-inside-a-function – Konrad Feb 02 '23 at 17:51
  • @user469485 You can't assign the caller's variable. You need to return the proxy and the caller can assign it to the variable. – Barmar Feb 02 '23 at 17:53