1

I have the following Javascript object:

var obj = (function (){
   return{
     functionOne: function(){}
     functionTwo: function(){
        $("#div").rotate(){
           callback: function(){
              functionOne(); // this doesn't work
           }
        });
     }
   }
}

When I am calling functionOne within a callback function from within functionTwo, functionOne is undefined. How can I call functionOne from withint the callback function of the rotate function (belongs to a plugin I use)?

2 Answers 2

4

You could try setting the object you're returning to a variable first, and then referencing that:

var obj = (function(){
    var o = {
        functionOne: function(){
            console.log('functionOne');
        },
        functionTwo: function(){
            $("#div").rotate({
                callback: function(){
                    o.functionOne();
                }
            });
        }
   };
   return o;
})();

obj.functionTwo(); // logs "functionOne"

You could also use something like:

var o;
return o = {
    ...
};

Both ways do the same thing; which one you want to use is a matter of personal preference and how readable you think they are.

Sign up to request clarification or add additional context in comments.

Comments

1

Inside functionTwo, this refers to the object. So if you save a reference, you can call the function like so:

var obj = (function (){
   return{
     functionOne: function(){},
     functionTwo: function(){
        var o = this;
        $("#div").rotate({
           callback: function(){
              o.functionOne(); // this does work
           }
        })
     }
   }
}());

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.