0

I'm trying to access method2 from within my each function. I'm getting the following error. How do I get this to work?

ReferenceError: method2 is not defined

method1: function() {
    $('tr[data-quantity]').each(function(value) {
        this.method2(value);
    })
},

method2: function(value) {
    console.log('test')
},

1 Answer 1

1

I assume that method1 and method2 belong to the same object with definition like this:

var obj = {
   method1: function(){},
   method2: function(){}
};

You can try:

    method1: function() {
        var self = this;
        $('tr[data-quantity]').each(function(value) {
            self.method2(value);
        })
    },

    method2: function(value) {
        console.log('test')
    },
Sign up to request clarification or add additional context in comments.

2 Comments

Yes, sorry I assumed it was known since I included the commas, anyhow it worked perfectly, what causes this to happen? Is it losing it's object reference do to the jquery each function?
@Code Junkie: this in javascript changes based on context: developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… . In your case, the context has changed when it enters the jquery.each which is the current item of the current iteration.

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.