A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from http://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy/Proxy/set below:

handler.set() - JavaScript | MDN

handler.set()

Baseline Widely available

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
const monster1 = { eyeCount: 4 };

const handler1 = {
  set(obj, prop, value) {
    if (prop === "eyeCount" && value % 2 !== 0) {
      console.log("Monsters must have an even number of eyes");
    } else {
      return Reflect.set(...arguments);
    }
  },
};

const proxy1 = new Proxy(monster1, handler1);

proxy1.eyeCount = 1;
// Expected output: "Monsters must have an even number of eyes"

console.log(proxy1.eyeCount);
// Expected output: 4

proxy1.eyeCount = 2;
console.log(proxy1.eyeCount);
// Expected output: 2
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.

target

The target object.

property

A string or Symbol representing the property name.

value

The new value of the property to set.

receiver

The this value for setters; see Reflect.set(). This is usually either the proxy itself or an object that inherits from the proxy.

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:

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:

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 Browser compatibility See also

RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4