Why object is not proxied like an argument in function

49 Views Asked by At

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?

1

There are 1 best solutions below

9
Konrad On

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);