-2
p.test = 'hello';    

$('#btn').on('click', function(event){
    console.log(this.test); //undefined
}).bind(this);

I'm trying to access my var inside a click, Im using bind but it's still logging 'undefined'.

Where am I going wrong?

panthro
  • 22,779
  • 66
  • 183
  • 324
  • 1
    `this` inside the click handler will be the DOM element which raised the event. You need to cache the reference to the `p` object outside of the handler first, then use that. Also, what are you expecting `bind(this)` to do? Bind accepts an event or a string. – Rory McCrossan Aug 11 '14 at 10:19

1 Answers1

2

The bind is placed wrong. You want to bind this to the event handler function, not to the jQuery collection of objects which are returned from the 'on' method.

Following sample should work:

$('#btn').on('click', function(event){
    console.log(this.test);
}.bind(this));

However, it's not very good practice. Better approach could be to reference the this object by some private variable. Common practice is to cache the this object into some local variable called self, that, _this or .. etc. For example you can use following approach:

var self = this;

$('#btn').on('click', function(event){
    console.log(self.test);
});
Viktor Bahtev
  • 4,858
  • 2
  • 31
  • 40