javascript - 在 IIFE 中使用实例属性

标签 javascript undefined 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); // <--
    })();
},

关于javascript - 在 IIFE 中使用实例属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27735190/

相关文章:

javascript - 如何将 jquery 调整大小功能添加到 WP 谷歌地图插件?

javascript - AngularJS 中的 IIFE

javascript - 未捕获的类型错误 : Cannot set property of undefined

Javascript 目标属性未定义

javascript - 无法读取未定义的属性 'src'

javascript - 使用 IIFE 时抛出 “` TypeError `: ` [0,1] ` is not a function”

javascript - JavaScript 中带有随机时间的“setinterval”

javascript - Switch Case 在 React Native 中不起作用

javascript - 更改属性时延迟渲染 dom 元素

node.js - express.js 实例化 Controller 中出现意外值 'this'