Derek
Derek

Reputation: 12378

Callback of a object member function? (Javascript)

var a = function(){

    this.x = function(){alert('apple');}
    this.y = function(callback){
        if(typeof callback == 'undefined' || callback == null)
            alert('argh')
        else
            callback();
    }
}
var foo = function(){alert('blah')};
var x = new a();
x.y(this.x); // why is this one undefined
x.y(foo); // works as expected

​ here is the jsfiddle link: http://jsfiddle.net/W7FyZ/2/

Why is it undefined when I pass in a object member function? Is there a way to pass a object member function as a callback?

Upvotes: 0

Views: 2551

Answers (2)

Umesh Patil
Umesh Patil

Reputation: 10685

I have just renamed your variable to clear the confusion.

var a = function(){
    this.x = function(){alert('apple');}
    this.y = function(callback){
        if(typeof callback == 'undefined' || callback == null)
            alert('argh')
        else
            callback();
    }
}
var foo = function(){alert('blah')};

Now, In the execution part:

var myA = new a();

Above line is assigning function a() variable 'myA'. So,Functions x() and y() of a(),should be called as myA.x() and myA.y().

x.y(myA.x); // it works 
x.y(this.myA.x) // This also works as this is a current window
x.y(foo); // works as expected

Upvotes: 0

James Allardice
James Allardice

Reputation: 165991

When you do x.y(this.x), this is a reference to the window, not an instance of a. I think what you may have intended was:

x.y(x.x);

Since x is an instance of a, this passes a reference to the x method of this instance of a to the y method of this instance of a.

When you do x.y(foo), foo is a function declared in this scope, so you pass a reference to the foo function into the y method of x.

Upvotes: 4

Related Questions