M41D
M41D

Reputation: 33

Why is "this" pointing to the "window Object" in the callback function?

var callBackFunc = {
    value       : "CallBackValue",
    getValue    : function(callback) {
        callback();
    }   
}
var TestingFunc = {
    value       : "TestingValue",
    alertValue  : function() {
        console.log(this);
    }
}

$(function() {
    callBackFunc.getValue(TestingFunc.alertValue);
});

I don't want answers to be able to use it properly, but I wonder why "this" points to Window Objects. Plz... Help me!!

Upvotes: 1

Views: 531

Answers (2)

user3555953
user3555953

Reputation:

The plain callback function reference is passed as a parameter to the callBackFunc.getValue, so there is no current this context will be formed with the plain function and the default this leads to the global object (window).

In order to form the context, we can use call, bind, apply methods.

Upvotes: 0

xianshenglu
xianshenglu

Reputation: 5319

because arguments passed by value which means

callBackFunc.getValue(TestingFunc.alertValue);

equals to

callBackFunc.getValue(function() {
        console.log(this);
    });

so ,callback() works

(function() {
            console.log(this);
        })()

so ,you get window.

If arguments passed by name ,in this case name is TestingFunc.alertValue,then you will get what you want like :

callback() equals to TestingFunc.alertValue()

However,js works by value not name

Upvotes: 3

Related Questions