Javascript - Collection Proxy apply

Introduction

Proxy apply is used to trap a function invocation.

It takes three arguments:

  • target: the target function whose behavior is being modified;
  • context: the context passed as this to target on invocation;
  • args: the arguments passed when applying the call.

The following code are applying a season discount on the final billing amount using the apply trap handler:

Demo

function getBill(amount) { 
    return amount; 
} 

const billHandler = { /*from   w w  w .  j  ava 2s . co  m*/
    apply: function(target, context, args) { 
        console.log("Applying Discount of 35%"); 
        return args[0] - (args[0] * 0.35); 
    } 
} 

const billProxy = new Proxy(getBill, billHandler); 

console.log(billProxy(300));

Result

Since the target object here is a function, these are also called as function traps.

You can alternatively have traps for .call() and .bind() methods also.

Related Topic