JavaScript | handler.apply() Method

The handler.apply() method in JavaScript is used as a trap for a function call. The value returned by this method is used as the result of a function call through a proxy.

Syntax:

const p = new Proxy(target, {
  apply: function(target, thisArg, argumentsList) {
  }
});

Parameters: This method accept three parameters as mentioned above and described below:

  • target: This parameter holds the target object.
  • thisArg: This parameter is used for the call.
  • argumentsList: This parameter contains the list as the argument and used for the call.

Return value: This method returns any value.

Below examples illustrate the handler.apply() method in JavaScript:



Example 1:

filter_none

edit
close

play_arrow

link
brightness_4
code

function sum(a, b) {
  return a + b;
}
  
const handler = {
  apply: function(target, thisArg, argumentsList) {
    console.log(`Calculate sum: ${argumentsList}`);
  
    return target(argumentsList[0], argumentsList[1])*14/3;
  }
};
  
const proxy1 = new Proxy(sum, handler);
  
console.log(sum(23, 4));
console.log(proxy1(23, 4));

chevron_right


Output:

27
"Calculate sum: 23, 4"
126

Example 2:

filter_none

edit
close

play_arrow

link
brightness_4
code

var str = function(arg1, arg2) {  
  console.log('geeks get (' + arg1 + ', ' + arg2 + ')');  
};  
var proxy = new Proxy(str, {  
  apply: function(target, thisArg, parameters) {  
   console.log('Geeksforgeeks');  
    
    return target.apply(thisArg, parameters);  
  }  
});  
proxy('Tutorial', 'Jobs');  
    
proxy.apply(null, ['Knowledge', 'internships']);  
proxy.call(null, 'Stipend', 'skills');

chevron_right


Output:

"Geeksforgeeks"
"geeks get (Tutorial, Jobs)"
"Geeksforgeeks"
"geeks get (Knowledge, internships)"
"Geeksforgeeks"
"geeks get (Stipend, skills)"

Supported Browsers: The browsers supported by JavaScript handler.apply() method are listed below:

  • Google Chrome
  • Firefox
  • Opera
  • Safari
  • Edge

full-stack-img




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.