jQuery $.proxy()

Description

jQuery $.proxy()

View in separate window

<!DOCTYPE html>
<html>
<head>
<script 
 src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js">
</script>/*from   ww  w .  j a  va  2 s .  c  o  m*/
<script>
$(document).ready(function(){
  var objPerson = {
    name: "CSS",
    age: 2,
    test: function(){
      $("p").after("Name: " + this.name + "<br> Age: " + this.age);
    }
  };
  $("button").click($.proxy(objPerson, "test"));
});
</script>
</head>
<body>

<button>Run test function</button>

<p></p>

</body>
</html>

The $.proxy method takes an existing function and returns a new one with a particular context.

$(selector).proxy(function,context)
$(selector).proxy(context,name)
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.



PreviousNext

Related