记录到控制台的JavaScript字段总是“未定义”

JavaScript field logged to console is always "undefined"

本文关键字:未定义 字段 控制台 JavaScript 记录      更新时间:2023-09-26

这是我第一次在JavaScript中使用对象,我使用了本教程中的1.1方法,我有这样的代码:

function MyClass() {
    this.currentTime = 0;
    this.start = function() {
        this.currentTime = new Date().getTime();
        console.log(this.currentTime); //this line prints the time i just set
        this.intervalID = setInterval(this.step, 25);
    };
    this.step = function() {
        var d = new Date().getTime();
        console.log(this.currentTime); //always prints "undefined" to the console
    };
    this.stop = function() {
        clearInterval(this.intervalID);
    };
}    

问题是在step()函数中,console.log(this.currentTime)总是打印"undefined",而this.currentTime是在start()函数中设置的。

为什么?我错过了什么?

您在每种情况下都使用功能this.fn的范围,这就是为什么您不将其添加到MyClass的范围。您必须存储this对象并使用它来添加属性。

function MyClass() {
    this.currentTime = 0;
    var self = this;
    this.start = function() {
        self.currentTime = new Date().getTime();
        console.log(self.currentTime); //this line prints the time i just set
        self.intervalID = setInterval(self.step, 25);
    };
    this.step = function() {
        var d = new Date().getTime();
        console.log(self.currentTime); //always prints "undefined" to the console
    };
    this.stop = function() {
        clearInterval(self.intervalID);
    };
}