使用Java脚本导出函数返回未定义

时间:2019-02-10 18:21:46

标签: javascript date undefined clock

只是一个序言;我大约三天前开始学习Javascript,因此我对某些事情的需求还不完全了解。

因此,我有一个正在运行的程序,该程序使用时钟来制作带有时间戳的文件夹,文件和日志。但是,当我从函数外部调用时间时,它只会返回undefined @ undefined:undefined:NaN,而在函数内部它会像正常的10/2/2019 @ 11:6:45

一样返回时间

function updateClock() {

    var currentdate = new Date();
    var day = currentdate.getDate();
    var month = currentdate.getMonth() + 1;
    var year = currentdate.getFullYear();
    this.date = " " + day + "/"
        + month + "/"
        + year;
    this.h = currentdate.getHours();
    this.m = currentdate.getMinutes();
    this.s = currentdate.getSeconds();
}

updateClock.prototype.run = function () {
    setInterval(this.update.bind(this), 1000);
};

updateClock.prototype.update = function () {
    this.updateTime(1);

    var time = " @ "
        + this.h + ":"
        + this.m + ":"
        + this.s;
    var datetime = this.date + time;
    console.log(datetime);
    return datetime;
};

updateClock.prototype.updateTime = function (secs) {
    this.s += secs;
    if (this.s >= 60) {
        this.m++;
        this.s = 0;
    };
    if (this.m >= 60) {
        this.h++;
        this.m = 0;
    };
    if (this.h >= 24) {
        this.day++;
        this.h = 0;
    }
};

var newclock = new updateClock();
newclock.run();




var timedate = updateClock.prototype.update();
console.log(timedate)

做什么以及如何解决?谢谢,我很感激!

1 个答案:

答案 0 :(得分:1)

您应该在类实例上而不是update上调用constructor

function updateClock() {

    var currentdate = new Date();
    var day = currentdate.getDate();
    var month = currentdate.getMonth() + 1;
    var year = currentdate.getFullYear();
    this.date = " " + day + "/"
        + month + "/"
        + year;
    this.h = currentdate.getHours();
    this.m = currentdate.getMinutes();
    this.s = currentdate.getSeconds();
}

updateClock.prototype.run = function () {
    setInterval(this.update.bind(this), 1000);
};

updateClock.prototype.update = function () {
    this.updateTime(1);

    var time = " @ "
        + this.h + ":"
        + this.m + ":"
        + this.s;
    var datetime = this.date + time;
    console.log(datetime);
    return datetime;
};

updateClock.prototype.updateTime = function (secs) {
    this.s += secs;
    if (this.s >= 60) {
        this.m++;
        this.s = 0;
    };
    if (this.m >= 60) {
        this.h++;
        this.m = 0;
    };
    if (this.h >= 24) {
        this.day++;
        this.h = 0;
    }
};

var newclock = new updateClock();
newclock.run();




var timedate = newclock.update();
console.log(timedate)