Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript: Difference between Reflect.get() and obj['foo']

Can't understand why I should use Reflect.get(obj, 'foo') instead of obj['foo'], or why the first one is useful as we can do the same thing using the good and old object bracket notation. Can someone please elaborate?

var obj = {foo: 'bar'};
obj['foo'];
Reflect.get(obj, 'foo');
like image 670
darksoulsong Avatar asked Jun 19 '17 20:06

darksoulsong


People also ask

What is reflect object in JavaScript?

Reflect is a built-in object that provides methods for interceptable JavaScript operations. The methods are the same as those of proxy handlers. Reflect is not a function object, so it's not constructible.

Why do we need reflect in JavaScript?

The primary use case of the Reflect object is it to make it easy to interfere functionality of an existing object with a proxy and still provide the default behavior. You can always just use the defined counterpart to the Proxy handler in the Reflect object and can be sure that the default behavior stays the same.

What is reflection object?

Reflection gives us information about the class to which an object belongs and also the methods of that class that can be executed by using the object. Through reflection, we can invoke methods at runtime irrespective of the access specifier used with them.

How do I find the name of an object?

The getName() method is used to get the names of the entities such as interface, class, array class, void etc. that are represented by the class objects. These names are returned in the form of a string.


1 Answers

Well, a pedantic answer to your question would be that they are entirely different: a property accessor returns a reference to a property, while Reflect.get returns its value.

From the practical standpoint that doesn't make any difference since property references are always dereferenced on the right side.

One practical usage of Reflect.get would be with its third argument, which, when combined with a Proxy, can be used to create different "views" of the same data.

let numbersView = obj => new Proxy(obj, {
    get(target, key, receiver) {
        return receiver(target[key])
    }
});

let decimal = x => String(x);

let english = x => {
    if (x === 1) return 'one';
    if (x === 2) return 'two';

};

let v = numbersView({
    a: 1,
    b: 2
});

console.log(Reflect.get(v, 'a', decimal))
console.log(Reflect.get(v, 'a', english))

This example is a bit made-up, but you got the idea.

like image 198
georg Avatar answered Oct 05 '22 21:10

georg