jQuery $.proxy() Method


The $.proxy() method in jQuery is used to take a function and returns a new one that will always have a particular context.

Syntax

The syntax is as follows −

$(selector).proxy(context,name)

Above, the context parameter is the name of object where the function can be found, whereas the name parameter is the existing function whose context will be changed

Example

Let us now see an example to implement the jQuery $.proxy() method −

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script>
   $(document).ready(function(){
      demo = function(){
         this.txt = "Object property!";
         $("p").click($.proxy(this.myClick, this));
      };
      demo.prototype.myClick = function(event){
         alert(this.txt);
         alert(event.currentTarget.nodeName);
      };
      var a = new demo();
   });
</script>
</head>
<body>
<h1>Demo Heading</h1>
<p>p element with demo text. Click it!</p>
</body>
</html>

Output

This will produce the following output −

Click on the p element to generate the following alert boxes −

Now, click on OK above −

Updated on: 11-Nov-2019

236 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements