Handlers for Functions

.apply()

A trap for a function call. (overrides the original function)


function f(...args) {
  return args[0];
}

var p = new Proxy(f, {
  apply: function(target, thisArg, argumentsList) {
    console.log('called: ' + argumentsList.join(','));
    let sum = 0;
    for (v of argumentsList) sum += v;
    return sum;
  }
});

console.log(p(1, 2, 3, 5));

called: 1,2,3,5 11

.construct()

A trap for the new operator. (overrides the original constructor)


var p = new Proxy(function() {
  console.log('Hi');
}, {
  construct: function(target, argumentsList, newTarget) {
    return { value: argumentsList[0] * 10 };
  }
});

var o = new p(10);
console.log(o.value);

100