Liron Harel
Liron Harel

Reputation: 11247

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

Upvotes: 1

Views: 91

Answers (2)

Jeff Shaver
Jeff Shaver

Reputation: 3355

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
           }
        })
     }
   }
}());

Upvotes: 1

tckmn
tckmn

Reputation: 59273

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.

Upvotes: 4

Related Questions