Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
250 views
in Technique[技术] by (71.8m points)

javascript - 将代理应用于对象(Applying proxy to an object)

Hi, I am trying to transform an object into a proxy, without changing the reference to the object:

(嗨,我正在尝试将一个对象转换为一个代理,而不更改对该对象的引用:)

Here is a simple class:

(这是一个简单的类:)

class Foo {
  constructor () {
    this.a = 'bar'
  }
}
const foo = new Foo()

Here is my Proxy:

(这是我的代理:)

const proxy = new Proxy(foo, {
  get () {
    return 'proxy-bar'
  },
  set () {
    // Don't do anything
    return true
  }
})

Here is what a normal use of this proxy does:

(这是此代理的常规用法:)

console.log(foo.a) // bar
console.log(proxy.a) // proxy-bar

Now, I want to keep using foo , but with the capabilities of proxy .

(现在,我想继续使用foo ,但要具有proxy的功能。)

So I tried to use Object.assign which seems to work only for the getter, but not for the setter.

(因此,我尝试使用Object.assign ,它似乎仅适用于getter,但不适用于setter。)

Is their something I miss?

(是我想念的吗?)

Object.assign(foo, proxy)
console.log(foo.a) // Getter works: proxy-bar

foo.a = 'proxy-proxy-bar'
console.log(foo.a) // Setter does not work: proxy-proxy-bar
  ask by Hammerbot translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can apply the proxy in your constructor and return it :

(您可以在构造函数中应用代理并将其返回:)

class Foo {
  constructor() {
    this.a = 'bar';
    return new Proxy(this, {
      get() {
        return 'proxy-bar'
      },
      set() {
        // Don't do anything
        return true
      }
    });
  }
}


const foo = new Foo();
foo.a = 'proxy-proxy-bar';
console.log(foo.a); // proxy-bar

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...