Jquery click handler and object oriented programming

I have a method in the class and in this method. I have a click event handler in a div element:

function MyClass(container)
{
   this.Container=container;
   this.PrepareHandlers = function()
    {

        $('#Div1').click(function() {
            alert(this.Container);
        });
    }; 
}

But since im is in the handler, "this" is an element click. Is access to the object of the object accessible from the handler declared inside the method?

+3
source share
3 answers
function MyClass(container)
{
   var self = this;
   this.Container=container;
   this.PrepareHandlers = function()
    {

        $('#Div1').click(function() {
            alert(self.Container);
        });
    }; 
}
+4
source

Correct me if I am wrong. "this" should refer to the function () {..} in a click?

0
source

jQuery 1.4 proxy method: http://api.jquery.com/jQuery.proxy/

function MyClass(container)
{
  this.Container=container;
  this.PrepareHandlers = function()
    {
      $('#Div1').click(function() {
        alert(jQuery.proxy(MyClass.Container, MyClass));
      });
    }
}
0

Source: https://habr.com/ru/post/1765654/


All Articles