在IIFE中使用实例属性

时间:2015-01-01 22:15:23

标签: javascript undefined iife

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

我的start方法出错:

  

未捕获的TypeError:undefined不是函数

我在控制台中记录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;
    }
};

1 个答案:

答案 0 :(得分:3)

在变量中存储对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); // <--
    })();
},