handler.set()
method is a trap for setting a property value.
The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
const p = new Proxy(target, {
set: function(target, property, value, receiver) {
}
});
The following parameters are passed to the
set()
方法。
this
is bound to the handler.
target
The target object.
property
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.
例如:
Suppose a script does
obj
.name = "jen"
,和
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.
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.
handler.set()
method is a trap for setting property value.
This trap can intercept these operations:
proxy
[
foo
] =
bar
and
proxy
.
foo
=
bar
Object.create(
proxy
)[
foo
] =
bar
Reflect.set()
If the following invariants are violated, the proxy will throw a
TypeError
:
undefined
as its
[[Set]]
属性。
false
return value from the
set()
handler will throw a
TypeError
异常。
The following code traps setting a property value.
const p = new Proxy({}, {
set: function(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
| 规范 |
|---|
|
ECMAScript (ECMA-262)
The definition of '[[Set]]' in that specification. |
| Desktop | Mobile | Server | |||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
set
|
Chrome 49 | Edge 12 | Firefox 18 | IE No | Opera 36 | Safari 10 | WebView Android 49 | Chrome Android 49 | Firefox Android 18 | Opera Android 36 | Safari iOS 10 | Samsung Internet Android 5.0 | nodejs 6.0.0 |
完整支持
不支持