The $.proxy() Method in jQuery accepts an existing function and returns a new one with a particular context. Generally, it is used for attaching events to an element where the context is pointing back to a different object.
Syntax:
html
Output:
html
Output:
$(selector).proxy(function, context)
$(selector).proxy(context, name)
- function: It holds the existing function name which is to be called.
- context: It shows the name of the object where the function lies.
- name: The function whose context is to be changed.
<!DOCTYPE html>
<html>
<head>
<title>
jQuery $.proxy() Method
</title>
<script src=
"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js">
</script>
<script>
$(document).ready(function() {
test = function() {
this.txt = "Property of Object";
$("h3").click($.proxy(this.myClick, this));
};
test.prototype.myClick = function(event) {
alert(this.txt);
alert(event.currentTarget.nodeName);
};
var x = new test();
});
</script>
</head>
<body style="text-align:center;">
<h1>Welcome to GeeksforGeeks!.</h1>
<div style="background-color:green">
<h3>Geeks for Geeks.</h3>
</div>
</body>
</html>
- Before clicking on the heading text h3:

- After clicking on the heading text h3:

- Click on OK button:

<!DOCTYPE html>
<html>
<head>
<title>
jQuery $.proxy() Method
</title>
<script src=
"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js">
</script>
<!-- Script to illustrate $.proxy() Method -->
<script>
$(document).ready(function(){
var objPerson = {
test: function() {
$("h2").after("GeeksforGeeks");
}
};
$("button").click($.proxy(objPerson, "test"));
});
</script>
</head>
<body style="text-align:center;">
<h1>Welcome to GeeksforGeeks!.</h1>
<div style="background-color:green">
<button>The $.proxy Method.</button>
<h2></h2>
</div>
</body>
</html>
- Before clicking on the button:

- After clicking on the button:
