简体   繁体   English

如何获得类财产?

[英]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". 但是动画末尾的功能无法识别“ 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. 您只有一个i变量,可以为所有回调共享。 You need to make a local i for each callback. 您需要为每个回调设置一个本地i Changing you callback from: 将回调从以下位置更改:

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

To: 至:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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