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. [see JS: Function Form vs Operator]const xx = {}; Reflect.set(xx, "dog", 3); console.assert(Object.hasOwn(xx, "dog")); console.assert(xx["dog"] === 3); // example of failed attempt to set property const xx = {}; Object.preventExtensions(xx); console.assert(Reflect.set(xx, "dog", 3) === false); console.assert(Object.hasOwn(xx, "dog") === false); Reflect.set(obj, key, val, thisValue)-
if the property is a setter property, thisValue is passed to the setter function as this-binding. If not a setter property, thisValue is ignored.
// 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.