The handler.set function assigns a value to a property. The set can maintain the order of insertion as an iterator. It comprises a collection of distinct items. If the assignment is successful, it returns true; if not, it returns false.
An Iterator is an object that specifies a sequence and may also provide a return value when it concludes.
Syntax
Example
set: function(target, property, value, receiver)
Parameters
target : The target object.
property : Name or Symbol of the property.
value : New value of the property.
receiver: Typically, this refers to the proxy itself. It can be assigned as a handler in an indirect manner, whether through the prototype chain or through several alternative methods.
Return value
Return a Boolean value.
Browser Support
| Chrome | 49 |
|---|---|
Edge |
12 |
| Firefox | 18 |
| Opera | 36 |
Example 1
Example
<script>
var proxy = { "a": 1, "b": 2 }
var pset = new Proxy(
proxy, {
set: function(y, idx, value) {
y[idx] = value * 10
}
}
)
pset.c = 3
for(var z in pset) {
document.writeln(z + "=" )
// print equal sign.
document.writeln(pset[z])
//expected output: a= 1 b= 2 c= 30
}
</script>
Output:
Output
a= 1 b= 2 c= 30
Example 2
Example
<script>
var x = { foo: 1 };
var proxy = new Proxy(x, {
set: function(target, name, value, proxy) {
document.writeln ('in set');
target[name] = value.toUpperCase();
}
});
proxy.foo = 'proxy method';
document.writeln(x.foo); // value stored on x is uppercase
//expected output: in set PROXY METHOD
</script>
Output:
Output
in set PROXY METHOD
Example 3
Example
<script>
const q={
foo:1
}
const p = new Proxy(q, {
set: function(target, prop, value, receiver) {
target[prop] = value;
document.writeln('property set: ' + prop + ' = ' + value);
//expected output: property set: a = 10
}
})
document.writeln('a' in p);
//expected output: false
p.a = 10;
// "property set: a = 10"
</script>
Output:
Output
false property set: a = 10