JavaScript Object Mirroring/One-way Property Syncing

后端 未结 2 618
无人及你
无人及你 2021-01-28 01:58

For security purposes, I have a need for a \"mirrored\" object. i.e. if I create object A, and shallow-clone a copy of A and call it B, whenever a property of A changes, I hope

2条回答
  •  不要未来只要你来
    2021-01-28 02:37

    Assuming you don't need to support IE8 and earlier, you can use getters to do that on modern browsers.

    function proxy(src) {
      var p = {};
      Object.keys(src).forEach(function(key) {
        Object.defineProperty(p, key, {
          get: function() {
            return src[key];
          }
        });
      });
      return p;
    }
    
    var a = {
      foo: "Original foo",
      bar: "Original bar"
    };
    var b = proxy(a);
    
    console.log(b.foo);    // "Original foo"
    a.foo = "Updated foo"; // Note we're writing to a, not b
    console.log(b.foo);    // "Updated foo"
    

提交回复
热议问题