0

I have this function inside of a javascript class:

this.checkSections = function(){
        jQuery('#droppable #section').each( function() {
            nextId = jQuery(this).next().attr('id');
            if (nextId != 'small' && nextId != 'large'){
                jQuery(this).remove();
                this.sections --;
                this.followArticles = 0;
            }else{
                articles = 0;
                obj = jQuery(this).next();
                while (nextId == 'small' || nextId == 'large'){
                    articles++;
                    obj = obj.next()
                    nextId = obj.attr('id');
                    //alert(nextId);
                }
                this.followArticles = articles;
                alert(this.sections);
            }
        });
    }

the alert(this.sections); (last lines) gives output of undefined although the sections is defined and used.

what could be the problem?

4
  • this does not relate to what you think it does. jQuery has overwritten it for use in $(this). I'm sure there is another method that's simpler, but I always use underscore.js's _.bind() function to pass through the parent's this data. Commented Jan 28, 2013 at 12:55
  • Inside the each function, this would be the element being iterated, and you're using $(this).remove() on the line above, so what makes you think this would reference a class on the next line ? Commented Jan 28, 2013 at 12:56
  • did you try alerting this.sections.value(); Commented Jan 28, 2013 at 13:01
  • Javascript: How to access a class attribute from a function within one of the class's functions Commented Jan 28, 2013 at 13:18

1 Answer 1

3

this is always a local variable and therefore it is overwritten in every function.

What you might do is pointing to your class e.g. var myClass = this; and use myClass instead of this.

 this.checkSections = function(){

    var myClass = this;

    jQuery('#droppable #section').each( function() {
        nextId = jQuery(this).next().attr('id');
        if (nextId != 'small' && nextId != 'large'){
            jQuery(this).remove();
            myClass.sections --;
            myClass.followArticles = 0;
        }else{
            articles = 0;
            obj = jQuery(this).next();
            while (nextId == 'small' || nextId == 'large'){
                articles++;
                obj = obj.next()
                nextId = obj.attr('id');
                //alert(nextId);
            }
            myClass.followArticles = articles;
            alert(myClass .sections);
        }
    });
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.