Nips
Nips

Reputation: 13870

How to access to class property?

I have this code:

function myClass() {

    this.tabs = new Array();

    myClass.prototype.focus_tab = function animateTab(nr){
        for(i=0;i<this.tabs.length;i++){
            $('#' + i + '-image').stop().animate(
                { left: '100px' },
                100 , function(){
                    this.tabs[i].step = 1;
                }
            );
        }
}

but function at the end of the animation does not recognize "this.tabs". How to do it well?

Upvotes: 0

Views: 55

Answers (2)

adeneo
adeneo

Reputation: 318202

It's in a a different scope, try:

function myClass() {
  this.tabs = new Array();

  myClass.prototype.focus_tab = function animateTab(nr){
     for(i=0;i<this.tabs.length;i++){
         var mytab = this.tabs[i];
         $('#' + i + '-image').stop().animate({ left: '100px' }, 100 , function(){
             mytab.step = 1;
         }
      );
  }
}

There are some other issues as well, but the comments on the question already adress some of them!

Upvotes: 3

Paul
Paul

Reputation: 141829

This is another example of the classic scoping issue. You only have one i variable, shared for all your callbacks. You need to make a local i for each callback. Changing you callback from:

function(){
    this.tabs[i].step = 1;
}

To:

(function(i){
    return function(){
        this.tabs[i].step = 1;
    }
})(i)

Upvotes: 0

Related Questions