Search code examples
javascriptjqueryfunctionoopcall

Call an object function from within a callback function in Javascript


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)?


Solution

  • 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.