Skip to content Skip to sidebar Skip to footer

ES6 Proxy: Set() Trap Not Triggering, When Setting Inside Target Object's Method

Example: let foo = {bar: 'baz', method() { this.bar = 'baz2' }} let fooProxy = new Proxy(foo, {set(target, key, val) { console.log('set trap triggered!') }}) fooProxy.bar = 'any v

Solution 1:

The set trap is not triggered because the this that you are accessing within method() is not the proxy but the original object foo. A proxy does not change the original object. You can see this by checking what this is inside method():

let foo = {
  method () {
    return this === fooProxy
  }
}
let fooProxy = new Proxy(foo, {})
document.write(foo.method()) //=> false

You could instead explicitly set the context of method() on invocation by using Function#call:

let foo = {bar: 'baz', method() { this.bar = 'baz2' }}
let fooProxy = new Proxy(foo, {set(target, key, val) { console.log('set trap triggered!') }})

fooProxy.bar = 'any value' //=> set trap triggered!
foo.method.call(fooProxy) //=> set trap triggered!

Solution 2:

You can also add the proxy to the object prototype.

SomeObject.prototype = new Proxy(
    SomeObject.prototype,
    SomeObjectHandlerProxy
);

instance = new SomeObject();

something like should work


Solution 3:

In foo.method you're not setting a propery through the proxy object, so obviously no trap is triggered. A Proxy does not modify the original object.


Post a Comment for "ES6 Proxy: Set() Trap Not Triggering, When Setting Inside Target Object's Method"