简体   繁体   中英

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?

When you do xy(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 xy(foo) , foo is a function declared in this scope, so you pass a reference to the foo function into the y method of x .

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM