在 IIFE 中使用实例属性

Using instance property in IIFE

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

我的启动方法出现错误:

Uncaught TypeError: undefined is not a function

我在控制台中记录了 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); // <--
    })();
},