The handler.set()
method is a trap for the [[Set]]
object internal method, which is used by operations such as using property accessors to set a property's value.
The handler.set()
method is a trap for the [[Set]]
object internal method, which is used by operations such as using property accessors to set a property's value.
new Proxy(target, { set(target, property, value, receiver) { } });
The following parameters are passed to the set()
method. this
is bound to the handler.
target
The target object.
property
The name or Symbol
of the property to set.
value
The new value of the property to set.
receiver
The object to which the assignment was originally directed. This is usually the proxy itself. But a set()
handler can also be called indirectly, via the prototype chain or various other ways.
For example, suppose a script does obj.name = "jen"
, and obj
is not a proxy, and has no own property .name
, but it has a proxy on its prototype chain. That proxy's set()
handler will be called, and obj
will be passed as the receiver.
The set()
method should return a boolean value.
true
to indicate that assignment succeeded.set()
method returns false
, and the assignment happened in strict-mode code, a TypeError
will be thrown. This trap can intercept these operations:
proxy[foo] = bar
and proxy.foo = bar
Reflect.set()
Or any other operation that invokes the [[Set]]
internal method.
If the following invariants are violated, the trap throws a TypeError
when invoked.
undefined
as its [[Set]]
attribute. false
return value from the set()
handler will throw a TypeError
exception. The following code traps setting a property value.
const p = new Proxy( {}, { set(target, prop, value, receiver) { target[prop] = value; console.log(`property set: ${prop} = ${value}`); return true; }, }, ); console.log("a" in p); // false p.a = 10; // "property set: a = 10" console.log("a" in p); // true console.log(p.a); // 10
Specification |
---|
ECMAScript Language Specification # sec-proxy-object-internal-methods-and-internal-slots-set-p-v-receiver |
Desktop | Mobile | Server | ||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
Chrome | Edge | Firefox | Opera | Safari | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | WebView Android | Deno | Node.js | ||
set |
49 | 12 | 18 | 36 | 10 | 49 | 18 | 36 | 10 | 5.0 | 49 | 1.0 | 6.0.0 |
© 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy/Proxy/set