JavaScript handler.apply() Method - JavaScript Tutorial

JavaScript handler.apply() Method

BLUF: This tutorial on JavaScript handler.apply() Method provides an in-depth look at JavaScript's core features. It includes practical examples and code snippets to help you master modern JS development.
Key Discovery: JavaScript handler.apply() Method

Understanding JavaScript handler.apply() Method is crucial for building dynamic, interactive web applications. Explore the examples below to see it in action.

The handler.apply function is utilized to intercept a function call. The value that the apply trap returns will also serve as the outcome of a function invocation via a proxy.

Syntax

Example

apply: function(target, thisArg, argumentsList)

Parameters

target : The target object.

thisArg : thisArg use for the call.

argumentsList: This refers to the collection of parameters utilized during the invocation.

Return value

This method can return any value.

Browser Support

Chrome 49
Edge 12
Firefox 18
Opera 36

Example 1

Example

var o = function(arg1, arg2) {

  document.writeln('proxy value(' + arg1 + ', ' + arg2 + ')');

};

var proxy = new Proxy(o, {

  apply: function(target, thisArg, parameters) {

    document.writeln('First exam..');

    

document.writeln("</br>");

    return target.apply(thisArg, parameters);

  }

});



proxy('23', '54');

Output:

Output

First exam.. 

proxy value(23, 54)

Example 2

Example

var str = function(arg1, arg2) {

  document.writeln('in x(' + arg1 + ', ' + arg2 + ')');

};

var proxy = new Proxy(str, {

  apply: function(target, thisArg, parameters) {

   document.writeln('in apply');

        document.writeln("<br/>");



    return target.apply(thisArg, parameters);

  }

});

proxy('direct1', 'direct2');



proxy.apply(null, ['add', 'add']);

proxy.call(null, 'string', 'string');

Output:

Output

in apply 

in x(direct1, direct2) in apply 

in x(add, add) in apply 

in x(string, string)

Example 3

Example

function p (a) 

{

  return a ;

}

var q = {

  apply: function(target, thisArg, argumentsList) {

   return target(argumentsList[0], argumentsList[1])*2;

  }};

var pro = new Proxy(p, q);

 document.writeln(p(56)); 

document.writeln("<br/>"); 

    document.writeln(pro(34));

Output:

Output

56 

68

Input Required

This code uses input(). Please provide values below:

Logic Practice
Install Logic Practice
Add to home screen for a faster app-like experience