JavaScript Object Mirroring/One-way Property Syncing

后端 未结 2 594
无人及你
无人及你 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:46

    You can setup the prototype chain for this:

    var a = {};
    var Syncer = function(){};
    Syncer.prototype = a;
    var b = new Syncer();
    
    a.foo = 123;
    b.foo; // 123
    
    b.bar = 456;
    a.bar // undefined
    

    Any property not set on b directly will be looked for on the prototype object, which is a.

    You can even wrap this up in a convenience function:

    var follow = function(source) {
      var Follower = function(){};
      Follower.prototype = source;
      return new Follower();
    }
    
    var a = {};
    var b = follow(a);
    
    a.foo = 123;
    b.bar = 456;
    
    a.foo; // 123
    b.foo; // 123
    
    a.bar; // undefined
    b.bar; // 456
    

提交回复
热议问题