1

I am trying to call a function via this reference inside of jquery scope:

var Person = function(){

    this.hello = function(){
        console.log("hello!");
    }

    this.jump = function(){
        $('.jump').on('click', function(){
            this.hello();
        });
    }

}

Then I do:

var p = new Person();

When I click over the .jump element, the console prints an error describing that hello is not a function. I am not sure what is happening here, I am assumming that this is trying to call a function inside of jquery (not sure about it).

So, googling a little bit I found the Jquery.proxy() function that could be helpfull in my situation, but every time I try to understand it my head want to explote.

manix
  • 14,537
  • 11
  • 70
  • 107

3 Answers3

2

Try this,

var self = this;


 this.jump = function(){
        $('.jump').on('click', function(){
            self.hello();
        });
    }
msapkal
  • 8,268
  • 2
  • 31
  • 48
2

Use $.proxy() like so:

var Person = function(){

    this.hello = function(){
        console.log("hello!");
    }

    this.jump = function(){
        $('.jump').on(
            'click',
            $.proxy(
                function() {
                    this.hello();
                },
                this
            )
        );
    }
}

Passing this as the 2nd argument to $.proxy() sends that context as the value of this inside the function defined in the first argument.

Derek
  • 4,575
  • 3
  • 22
  • 36
1

when you refer to "this" inside onclick, by default this refers to the DOM element found in the value of event.target

$('.jump').on('click', function(event) {
     this.hello() /// <<-- this == event.target =~ $('.jump')
}

so, fortunately, you can use a closure

var self = this;
this.jump = function(){
    $('.jump').on('click', function(){
        self.hello();
    });
}
rnrneverdies
  • 15,243
  • 9
  • 65
  • 95
  • 1
    In your first example, it should be clarified that by default `this` refers to the DOM element found in the value of `event.target`. – Derek Aug 14 '14 at 04:19