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

Can't figure out why I should use Reflect.get(obj, 'foo')

instead obj['foo']

, or why the first one is useful, as we can do the same using the note of good and old objects. Can anyone comment?

var obj = {foo: 'bar'};
obj['foo'];
Reflect.get(obj, 'foo');

      

+3


source to share


2 answers


Well, the pedantic answer to your question would be that they are completely different: the accessor property returns a reference to the property, but it Reflect.get

returns its own value.

From a practical point of view, that doesn't make any difference, since property references are always dereferenced on the right side.

One practical use Reflect.get

will have to do with its third argument, which in combination with 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))
      

Run codeHide result


This example is a bit compiled, but you got the idea.

+4


source


No difference.

Taken from MDN documentation:

The static method Reflect.get () works like getting a property of an object (target [propertyKey]) as a function. Reflect.get () | MDN



The only difference is: Reflect.get()

Will throw TypeError

if the given value is not object

.

obj[prop]

will throw ReferenceError

if obj

undefined, but otherwise just return undefined

.

Indeed, I would argue that it only exists to give a Reflect

complete API, but there should be no downside to using the syntax obj[prop]

.

+2


source







All Articles