JS: Reflect.set
(new in ECMAScript 2015)
Reflect.set(obj, key, val)-
- Set a value to a proprety of object.
- Return
trueif success, elsefalse.
🟢 TIP: This function is similar to the syntax
obj[key] = val, but in a function form. Function form lets you manipulate expressions at run-time.const xx = {}; Reflect.set(xx, "p", 3); console.assert(Object.hasOwn(xx, "p")); console.assert(xx["p"] === 3); // example of failed attempt to set property const xx = {}; Object.preventExtensions(xx); console.assert(Reflect.set(xx, "p", 3) === false); console.assert(Object.hasOwn(xx, "p") === false); Reflect.set(obj, key, val, thisValue)-
thisValue is passed as value of this (binding) for Getter Setter Properties.
// apple. has a setter property named color. // it stores value to color_val. const apple = { color_val: "", set color(x) { this.color_val = x; }, }; // grape. has a property named color_val. const grape = { color_val: "" }; // set apple.color to green Reflect.set(apple, "color", "green"); // check console.assert(apple.color_val === "green"); // set setter method apple.color to red, but on object grape Reflect.set(apple, "color", "red", grape); // check console.assert(grape.color_val === "red");
Difference Between Reflect.Set vs Property Assignment Syntax
Reflect.set(obj, key, val)
is similar to the operator form
obj[key] = val
The difference are:
Reflect.setis a function. The function form is useful in functional programing or generating code at run time.Reflect.setalso return true/false depends on success. The assignment form has no proper way to know if the operation is succesful.Reflect.setprovides a this (binding) for Getter Setter Properties.