ES6 - handler.apply()


Advertisements

The following example defines a function rectangleArea, which takes width and height as parameters and returns the area of the rectangle. The program creates a proxy and defines a handler object for the rectangleArea function. This handler object verifies the number of parameters passed to the function before the function is executed. The handler object throws an error if two parameters are not passed to the function.

<script>
   function rectangleArea(width,height){
      return width*height;
   }
   const handler = {
      apply:function(target,thisArgs,argsList){
      console.log(argsList);
      //console.log(target)
      if(argsList.length == 2){
         return Reflect.apply(target,thisArgs,argsList)
      }
         else throw 'Invalid no of arguments to calculate'
      }
   }

   const proxy = new Proxy(rectangleArea,handler)
   const result = proxy(10,20);
   console.log('area is ',result)
   proxy(10) // Error
</script>

The output of the above code will be as mentioned below −

[10, 20]
area is 200
[10]
Uncaught Invalid no of arguments to calculate
Advertisements