John Smith
John Smith

Reputation: 6269

Call anonymous function on object

Normally I do callbacks like this: The Object that invokes the callback has this methods:

this.set_success_callback = function(obj, func){
    this.success_callback_obj  = obj;
    this.success_callback_func = func;
}

this.make_success_callback = function(msg){
    this.success_callback_obj[this.success_callback_func](msg);
}

Then In When I setup the Object I assgin the callback like this:

 var obj = new ...
     obj.set_success_callback(this, "sayHello");

This works as expected. But when I want to define the callback like this:

  obj.set_success_callback(this, this.sayHello);

And change the make_success_callback function to:

 this.success_callback_ob.call(this.success_callback_func, msg)

I get this error:

Object [object Object] has no method 'call'

What do I have to change to make it work? How can I invoke the function sayHello on this? Thanks

Upvotes: 0

Views: 81

Answers (1)

gilly3
gilly3

Reputation: 91657

You just mixed up the object with the function. It should be:

this.success_callback_func.call(this.success_callback_ob, msg)

A Function has a .call() method, that takes a context object as the first argument. Object has no .call() method.

Upvotes: 2

Related Questions