JavaScript: Reflect.set

By Xah Lee. Date: . Last updated: .

New in JS2015.

Reflect.set(obj, key, val)
  • Similar to obj[key] = val, but in a function form, so can be constructed at run-time.
  • Returns true if success, else false.
const xx = {};
Reflect.set(xx, "p", 3);

console.log(xx.hasOwnProperty("p"));
console.log(xx["p"] === 3);
// example of failed attempt to set property
const xx = {};
Object.preventExtensions(xx);
console.log(Reflect.set(xx, "p", 3) === false);
console.log(xx.hasOwnProperty("p") === false);
Reflect.set(obj, key, val, thisValue)
thisValue is passed as value of this Binding for Getter/Setter Properties.
let aa = [];

const jj1 = {
  p1: 1,
  set p2(x) {
    aa = [this.p1, x];
  },
};

const jj2 = { p1: 2 };

Reflect.set(jj1, "p2", 1);
console.log(aa); // [ 1, 1 ]

Reflect.set(jj1, "p2", 1, jj2);
console.log(aa); // [ 2, 1 ]

JavaScript: Set Property

BUY
ΣJS
JavaScript in Depth

JS Obj Reference

Reflect