$.proxy() Method - Javascript jQuery Method and Property

Javascript examples for jQuery Method and Property:proxy

Description

The $.proxy method returns a new function with a particular context for an existing function .

Syntax

 Table:
 Parameter     Description
 function      The existing function to be called
 context       The name of the object where the function lies
 name          The existing function whose context will be changed (should be a property of the context object).

Demo Code

ResultView the demo in separate window

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function(){

test = function(){//ww  w  . jav a  2  s.c  o  m
    this.txt = "This is an object property";
    $("div").click($.proxy(this.myClick, this));
};

test.prototype.myClick = function(event){
    console.log(this.txt);
    console.log(event.currentTarget.nodeName);
};

var x = new test();

});
</script>
</head>
<body>

<div>This is a div element.</div>

</body>
</html>

Syntax 2

Demo Code

ResultView the demo in separate window

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function(){

test = function(){//from  w w  w .  j  ava2  s .c  o m
    this.txt = "property";
    $("div").click($.proxy(this.myClick, this));
};

test.prototype.myClick = function(event){
    console.log(this.txt);
    console.log(event.currentTarget.nodeName);
};

var x = new test();

});
</script>
</head>
<body>

<div>This is a div element.</div>

</body>
</html>

Related Tutorials