如何在JS中的setTimeout中调用this.function?

Jos*_*osh 5 javascript

我有以下JS:

function TrackTime() {

    this.CountBack = function(secs) {
        setTimeout(function(){this.CountBack(secs)}, SetTimeOutPeriod);
    }

}
Run Code Online (Sandbox Code Playgroud)

我试过这个关闭(见上文)以及其他十几种方式.我似乎无法在任何浏览器中使用它.不在"类"函数中调用时,setTimeout函数工作正常.有人可以帮我这个吗?

Cha*_*ndu 9

这是因为执行函数时"this"范围的变化.

试试这个 - 这招

    function TrackTime() {  
        this.CountBack = function(secs) {         
            var that = this;

            setTimeout(function(){that.CountBack(secs)}, SetTimeOutPeriod);     
        };
    } 
Run Code Online (Sandbox Code Playgroud)