Categories
ECMAScript Javascript

Proxy API

/**
 * Proxy APIs are used to define proxy/custom behaviors for original ones.
 * It is another form of meta programming based on 
 * target : it can be targetted function or class or array to make proxy for
 * handler : it is an object which properties are handler methods
 * traps : Methods those provides property access
 */

//defining targets
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}`; 
	}
}

function calculateRectangleArea(length, width){
	return "rectangle area is : " + (length*width);
}


//Defining handler which contains properties as methods
const handler = {
		apply : function(target,thisArgs,argsList){
			if(argsList.length==2){
				return Reflect.apply(target,thisArgs,argsList);
			} else {
				throw new Error("Illegal number of arguments :: " + argsList.legth);
			}
		},
		construct : function(target,argsList){
			if(argsList.length>=2){
				return Reflect.construct(target,argsList);
			} else {
				throw new Error("Illegal number of arguments for construct:: " + argsList.legth);
			}
		},
		get : function(target,property){
			return "lastName is : " + Reflect.get(target,property).toLowerCase();
		},
		set : function(target,property,value){
			value = value.toUpperCase();
			return Reflect.set(target,property,value);
		},
		has : function(target,property){
			console.log(`is property ${property} present : `, Reflect.has(target,property));
		}
}

//Proxy.Apply demo - To call method through Proxy Apply
const proxyRectangle = new Proxy(calculateRectangleArea,handler);
console.log("Rectangle area : "+ proxyRectangle(15,20));
//console.log("Rectangle area : "+ proxyRectangle(15));

//Proxy.construct - to construct Object from Proxy
const employeeProxy = new Proxy(Employee,handler);
const employeeDisha = new employeeProxy("Disha","Sharma","Software Tester");
console.log("Disha Role ::"+employeeDisha.role);

//Proxy.get - to get value of object property through proxy
const employeeNeha = new Employee("Neha","Sharma","Developer");
const nehaProxy = new Proxy(employeeNeha,handler);
console.log("nehaproxy get last name : "+nehaProxy.lastName);

//Proxy.has- to check if object has property
Reflect.has(nehaProxy,"firstName");


Output

Leave a comment

Design a site like this with WordPress.com
Get started