簡體   English   中英

在IIFE中使用實例屬性

[英]Using instance property in IIFE

如何在方法中的IIFE中使用實例變量?

我的啟動方法出現錯誤:

未捕獲的TypeError:undefined不是函數

我在控制台中記錄了this.element ,但確實沒有定義它,但是在IIFE之外,它工作正常。

如何使它在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); // <--
    })();
},

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM