Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript: Object's this.var inside jQuery method

I can't figure this one out:

I have a function, e.g.

function test () {
  this.rating = 0;
  $j('#star_rating a').click(function() {
    alert(this.rating);
  });
}

var foo = new test();

On click it alerts "undefined". What is wrong? Please help.

like image 897
mvbl fst Avatar asked Aug 07 '26 23:08

mvbl fst


1 Answers

Inside the .click() the this refers to the item clicked. So the context is different than when you set rating. Those two thiss are different.

You need to conserve the context somehow.

Also, you may want to return false; or event.preventDefault() if you are clicking on a link and you don't want the page to refresh

function test () {

  this.rating = 0;
  var oldThis = this;           // Conserving the context for use inside .click()

  $j('#star_rating a').click(function() {

       alert(oldThis.rating);

       return false; // Use this if you don't want the page to change / refresh
  });
}

var foo = new test();

Try it out with this jsFiddle

like image 79
Peter Ajtai Avatar answered Aug 10 '26 12:08

Peter Ajtai



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!