在 IIFE 中使用实例属性

Using instance property in IIFE

本文关键字:实例 属性 IIFE      更新时间:2023-09-26

如何在方法中使用IIFE中的实例变量?

我的启动方法出现错误:

捕获的类型错误:未定义不是函数

我在控制台中登录了this.element,它确实显示为未定义,但在 IIFE 之外它工作正常。

如何让它在 IIFE 内工作?我尝试在 IIFE 中将其作为参数传递,但这也没有用。

function LiveDateTime(element) {
    'use strict';
    this.element = element;
}
LiveDateTime.prototype = {
    setLocale: function (locale) {
        this.locale = locale;
    },
    setOffsetSeconds: function (seconds) {
        this.offsetSeconds = seconds;
    },
    setDaylightSavingTimeSeconds: function (seconds) {
        this.daylightSavingTimeSeconds = seconds;
    },
    start: function () {
        (function update() {
            var now = new Date();
            var now = new Date(
                now.getUTCFullYear(),
                now.getUTCMonth(),
                now.getUTCDate(),
                now.getUTCHours(),
                now.getUTCMinutes(),
                now.getUTCSeconds(),
                now.getUTCMilliseconds()
            );
            this.element.innerHTML = now.toLocalString('fr-FR'); // <--
            this.timeoutId = setTimeout(update, 50); // <--
        })();
    },
    stop: function () {
        clearTimeout(this.timeoutId);
        this.timeoutId = 0;
    }
};

在变量中存储对this的引用,如下所示

start: function() {
    var self = this;
    (function update() {
        var now = new Date();
        var now = new Date(
            now.getUTCFullYear(),
            now.getUTCMonth(),
            now.getUTCDate(),
            now.getUTCHours(),
            now.getUTCMinutes(),
            now.getUTCSeconds(),
            now.getUTCMilliseconds()
        );
        self.element.innerHTML = now.toLocalString('fr-FR'); // <--
        self.timeoutId = setTimeout(update, 50); // <--
    })();
},