JavaScript: Difference Between Reflect.get () and obj ['foo']
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))
This example is a bit compiled, but you got the idea.
source to share
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]
.
source to share