为什么"这个"指向"窗口对象"在回调函数中?

时间:2018-04-10 08:15:33

标签: javascript callback this

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

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

我不想要答案能够正确使用它,但我想知道为什么"这个"指向Window Objects。 Plz ......帮助我!!

2 个答案:

答案 0 :(得分:3)

arguments传递value,这意味着

callBackFunc.getValue(TestingFunc.alertValue);

等于

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

所以,callback()正常工作

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

所以,你得到window

如果arguments name已经过name,在这种情况下TestingFunc.alertValuecallback(),那么您将得到您想要的内容:

TestingFunc.alertValue()等于js

但是,value适用于name而不是str = "xxxxxxx" dec_str = decode(str) while(dec_str != str) str = dec_str; dec_str = decode(str);

答案 1 :(得分:0)

普通回调函数引用作为参数传递给callBackFunc.getValue,因此没有使用plain函数形成当前this上下文,并且默认this导致全局对象(窗口)。

为了形成上下文,我们可以使用call, bind, apply方法。