This is an experimental technology, part of the ECMAScript 6 (Harmony) proposal.
Because this technology's specification has not stabilized, check the compatibility table for usage in various browsers. Also note that the syntax and behavior of an experimental technology is subject to change in future version of browsers as the spec changes.
Summary
The handler.set() method is a trap for setting a property value.
Syntax
var p = new Proxy(target, {
set: function(target, property, value, receiver) {
}
});
Parameters
The following parameters are passed to the set method. this is bound to the handler.
target- The target object.
property- The name 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
sethandler can also be called indirectly, via the prototype chain or various other ways. - For example, suppose a script does
obj.name = "jen", andobjis not a proxy, and has no own property.name, but it has a proxy on its prototype chain. That proxy'ssethandler will be called, andobjwill be passed as the receiver.
Return value
The set method should return a boolean value. Return true to indicate that assignment succeeded. If the set method returns false, and the assignment happened in strict-mode code, a TypeError will be thrown.
Description
The handler.set method is a trap for setting property value.
Interceptions
This trap can intercept these operations:
- Property assignment:
proxy[foo] = barandproxy.foo = bar - Inherited property assignment:
Object.create(proxy)[foo] = bar Reflect.set()
Invariants
If the following invariants are violated, the proxy will throw a TypeError:
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 data property.
- Cannot set the value of a property if the corresponding target object property is a non-configurable accessor property that has
undefinedas its [[Set]] attribute.
Examples
The following code traps setting a property value.
var p = new Proxy({}, {
set: function(target, prop, value, receiver) {
console.log("called: " + prop + " = " + value);
return true;
}
});
p.a = 10; // "called: a = 10"
Specifications
| Specification | Status | Comment |
|---|---|---|
| ECMAScript 6 (ECMA-262) The definition of '[[Set]]' in that specification. |
Draft | Initial definition. |
Browser compatibility
| Feature | Chrome | Firefox (Gecko) | Internet Explorer | Opera | Safari |
|---|---|---|---|---|---|
| Basic support | ? | 18 (18) | ? | ? | ? |
| Feature | Android | Chrome for Android | Firefox Mobile (Gecko) | IE Mobile | Opera Mobile | Safari Mobile |
|---|---|---|---|---|---|---|
| Basic support | ? | ? | 18.0 (18) | ? | ? | ? |