简体   繁体   中英

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?

It's in aa 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!

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM