Junior — Middle
Can you explain what the Reflect class in JavaScript is and what it is used for?
sobes.tech AI
Answer from AI
The question concerns JavaScript, but the module specified is Golang — I will answer in JavaScript.
Reflect is a built-in object in JavaScript that provides methods for intercepting and controlling operations on objects, such as getting and setting properties, calling functions, creating objects, etc. It serves as a set of utilities for metaprogramming.
The main purpose of Reflect is to provide functionality similar to the internal methods of objects, but in the form of regular functions, which simplifies working with proxies and dynamic operations.
Example of usage:
const obj = {a: 1};
// Getting a property
console.log(Reflect.get(obj, 'a')); // 1
// Setting a property
Reflect.set(obj, 'b', 2);
console.log(obj.b); // 2
// Checking for the existence of a property
console.log(Reflect.has(obj, 'a')); // true
// Calling a function
function sum(x, y) { return x + y; }
console.log(Reflect.apply(sum, null, [1, 2])); // 3
Thus, Reflect helps to manage objects and their behavior more explicitly and safely.