Sunday, November 17, 2024
Google search engine
HomeLanguagesJavascriptJavaScript Handler apply() Method

JavaScript Handler apply() Method

JavaScript 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 accepts 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 is used for the call.

Return value: This method returns any value.

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

Example 1: In this example, we will calculate the sum of the numbers using the handler.apply() method in JavaScript.

javascript




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));


Output: 

27
"Calculate sum: 23, 4"
126

Example 2: In this example, we will print values using the handler.apply() method in JavaScript.

javascript




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


Output: 

"Geeksforneveropen"
"neveropen get (Tutorial, Jobs)"
"Geeksforneveropen"
"neveropen get (Knowledge, internships)"
"Geeksforneveropen"
"neveropen get (Stipend, skills)"

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

  • Google Chrome 49 and above
  • Edge 12 and above
  • Firefox 18 and above
  • Opera 36 and above
  • Safari 10 and above

We have a complete list of Javascript Proxy/handler methods, to check those go through the Javascript Proxy/handler Reference article.

Whether you’re preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, neveropen Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we’ve already empowered, and we’re here to do the same for you. Don’t miss out – check it out now!

RELATED ARTICLES

Most Popular

Recent Comments