REFLECT IN JAVASCRIPT


Share

DEFINITION

In General, Reflection means ability of the computer programs to manipulate properties and methods of javascipt objects at run time.

Reflect API was introduced in ES6. Reflect API provides varioys static methods to manipulate objects properties at runtime.

All of the methods in Reflects API are static. So Reflect API cannot be instantiated using new operator.


Reflect API

Reflect.apply(target, thisArgumetn, argumentsList)
Calls the target function with argument specified by argumentsList

Reflect.construct(target, argumentsList[. newTarget])
It is same as new operator, But as a function, The new operator as a function. Is also provides the option to specify a different prototype.

Reflect.defineProperty(target, propertyKey, attributes)
Similar to Object.defineProperty(). Returns a Boolean that is true if the property was successfully defined.

Reflect.deleteProperty(target, propertyKey)
The delete operator as a function. Equvalent to calling delete target[propertyKey].

Reflect.apply(Math.max, Math, [10, 20, 30]);

//30


const person1 = Reflect.construct(person, ['deepak'], Manager)

//creates a new object for the class Person. But target class as manager

console log(person1 instanceof Manager)

true


Reflect.defineProperty (person1, 'age', {value: 22});

//defines a property 'age' with value as 22

Reflect.delteProperty(person2, 'name')

//is equivalent to delete operator


Reflect API (Cont...)


Reflect.get(target, propertyKey[, reciver])
Returns the value of the property, Works like getting a property from an object (target[propertyKey]) as a function.

Reflect.getOwnPropertyDescriptor(target, propertyKey)
Similar to Object.getOwnPropertyDescriptor(). Returns a property descriptor of the given property if it exists on the object, undefined otherwise.

Reflect.getPrototypeOf(target)
Returns a Boolean indicating whether the target has the property.

Reflect.get(person1, ['name']);

//Deepak


Reflect.getOwnPropertyDescriptor(person1, 'age');

// { value 22, writable: false, enumerable: true, configurable: false }


Reflect.getPropertyOf ( person1);

//Person {}

Reflect.has(person1, 'age');

//true


Share Author Section