/**
* Reflect APIs are set of APIs that allow us to inspect, modify classes,objects,properties, methods at runtime
*
*/
//Demo of Reflect.Apply
//Reflect.apply(target, thisArgument, argumentsList)
//target method/function to call
//object to be treated as This value for call.
//argumentsList is array of arguments
function calculateRectangleArea(length, width){
return "rectangle area is : " + (length*width)+ " "+this.unit;
}
var areaUnit = {unit : "m2"};
var argsList = [25,30];
const result = Reflect.apply(calculateRectangleArea,areaUnit,argsList);
console.log(result);
//Demo of Reflect.construct
//Reflect.construct(target,argumentList[,newTarget])
class Employee{
constructor(firstName, lastName, role="Software Developer"){
this.firstName = firstName;
this.lastName = lastName;
this.role = role;
}
get info(){
return `Name : ${this.lastName} ${this.firstName} \n role : ${this.role}`;
}
}
class Person{
get info(){
return `Mr/Ms. ${this.firstName} ${this.lastName}`;
}
}
var args = ["Disha", "Khera"];
var employeeDisha = Reflect.construct(Employee, args,Person);//employeeDisha is constructed from Employee constructor, but later class type of employeeDisha changed to Person
var employeeNeha = Reflect.construct(Employee,["Neha","Singh"],Person);
console.log(`details of Disha : ${employeeDisha.info}`);
console.log(`Disha is a person ? : ${employeeDisha instanceof Person}`);
console.log(`Disha is a Employee ? : ${employeeDisha instanceof Employee}`);
//Demo of Reflect.get
//Reflect.get(target,propertyKey[,receiver]) to set value to target object property
//target : target object on which to get the property
//propertyKey : name of property to get
//Receiver : to get property from receiver class
console.log(`details of Disha :: ${employeeDisha.info}`);
console.log("details of Disha as employee:: ",Reflect.get(employeeDisha,"firstName",Employee));
console.log("details of Disha as a person employee:: ",Reflect.get(employeeDisha,"firstName",Person));
//Demo of Reflect.set
//Reflect.set(targetObject,propertyKey, value[,receiver])
//targetObject : object or object type to get property value
//propertyKey : name of property key to set
//value : value to set
//receiver : optional argument to target if a setter is encountered
Reflect.set(employeeDisha,"lastName","Kaur")
console.log(`After setting lastName : ${employeeDisha.info}`);
Reflect.set(Employee,"lastName","Jat",employeeNeha);
console.log(`After setting lastName : ${employeeDisha.info}`);
console.log(`After setting lastName : ${employeeNeha.info}`);
//Demo of Reflect.has
//Reflect.has(target, propertyKey) to check if target object has property key
console.log(`employee Disha has firstName : `, Reflect.has(employeeDisha,"firstName"));
console.log(`employee Neha has firstName : `, Reflect.has(employeeNeha,"firstName"));
console.log(`employee Disha has info : `, Reflect.has(employeeNeha,"info"));
console.log(`employee Neha has info : `, Reflect.has(employeeNeha,"info"));
Output
