'这个'概念在javascript中的对象中

aps*_*943 4 javascript

我很抱歉这个简单的问题.但我只是想知道下面的代码中发生了什么.

var indexobj = {
    test : 1,
    testFunction : function() {
        document.getElementById('AA').innerHTML = indexobj.test++;
        //this is i wanted
        document.getElementById('BB').innerHTML = this.test++;
        //NaN
        setTimeout(indexobj.testFunction,1000);
    },
}
setTimeout(indexobj.testFunction,1);
Run Code Online (Sandbox Code Playgroud)

以下是示例链接

http://jsfiddle.net/apss/JR5Xk/28/

为什么在这个例子中'testFunction'函数中的'this'并不意味着'indexobj'这个对象?谢谢你的帮助.

dfs*_*fsq 6

因为setTimeout全局对象上下文中运行回调函数,意味着作为对象indexobj.testFunction调用.thiswindow

所以你可以做到

setTimeout(function() {
    indexobj.testFunction();
},1000);
Run Code Online (Sandbox Code Playgroud)

或者Function.prototype.bind用于创建具有正确上下文的包装函数:

setTimeout(indexobj.testFunction.bind(indexobj), 1000);
Run Code Online (Sandbox Code Playgroud)

ES2015的另一个现代选项是使用保留词汇上下文的箭头功能:

setTimeout(() => indexobj.testFunction(), 1000);
Run Code Online (Sandbox Code Playgroud)