handler.set()
Baseline Widely available
This feature is well established and works across many devices and browser versions. It’s been available across browsers since September 2016.
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.
Try it
Syntax
new Proxy(target, {
set(target, property, value, receiver) {
}
})
Parameters
The following parameters are passed to the set()
method. this
is bound to the handler.
Return value
The set()
method must return a Boolean
indicating whether or not the assignment succeeded. Other values are coerced to booleans.
Many operations, including using property accessors in strict mode, throw a TypeError
if the [[Set]]
internal method returns false
.
Description
Interceptions
This trap can intercept these operations:
- Property assignment:
proxy[foo] = bar
andproxy.foo = bar
Reflect.set()
Or any other operation that invokes the [[Set]]
internal method.
Invariants
The proxy's [[Set]]
internal method throws a TypeError
if the handler definition violates one of the following invariants:
- Cannot change the value of a property to be different from the value of the corresponding target object property, if the corresponding target object property is a non-writable, non-configurable own data property. That is, if
Reflect.getOwnPropertyDescriptor()
returnsconfigurable: false, writable: false
for the property ontarget
, andvalue
is different from thevalue
attribute in thetarget
's property descriptor, then the trap must return a falsy value. - Cannot set the value of a property if the corresponding target object property is a non-configurable own accessor property that has an undefined setter. That is, if
Reflect.getOwnPropertyDescriptor()
returnsconfigurable: false, set: undefined
for the property ontarget
, then the trap must return a falsy value.
Examples
Trap setting of a property value
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
Specifications
Specification |
---|
ECMAScript Language Specification # sec-proxy-object-internal-methods-and-internal-slots-set-p-v-receiver |
Browser compatibility
BCD tables only load in the browser