JavaScript Object Mirroring/One-way Property Syncing

那年仲夏 提交于 2019-12-02 08:46:14

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"

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
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!