如何将代理与展开运算符或 object.assign 一起使用?

问题描述 投票:0回答:1

我需要在回调函数中将方法和存储绑定到“this”,但是当我使用扩展运算符时,它不起作用。 据我所知,这样做的原因是扩展运算符返回原始的副本。因此代理永远不会被触发。

在这种情况下我该怎么做才能触发代理?

const setup = function (options, cb) {
  let store = new Proxy(options.store, {
    set(target, prop, value) {
      console.log(`changed ${prop} from ${target[prop]} to ${value}`);
      target[prop] = value;
      return true;
    },
  });
  cb.bind(store)(); // Works as expected
  // cb.bind({ ...store, ...methods })(); // Doesn't work
};

setup(
  {
    store: {
      n: 123,
    },
  },
  function () {
    this.n = 456;
  }
);
javascript node.js bind es6-proxy
1个回答
0
投票

删除未绑定的

methods
变量后,您的示例将按预期工作。

您不会看到正在打印的消息。这是可以预料的,因为表达式

{...store}
本质上克隆了(代理)对象
store
,其效果是创建一个新的(常规)对象并将其传递给
bind
并在那里进行修改。

最新问题
© www.soinside.com 2019 - 2024. All rights reserved.