这很奇怪...在function getNumber()中,变量mostRecent没有访问外部变量var mostRecent

我在控制台中看到console.log(mostRecent)显示mostRecent已更新,但是当我执行elements.mostRecent时,它仍显示默认值。

var elements = function () {

    var mostRecent = { "timeStamp" : "0" };
    var timeCollection = [];

    function getElements() {
        var trElements = document.getElementsByTagName("tr");

        for (var i = 1; i < trElements.length; ++i) {
            var obj = {
                "action" : trElements[i].children[5].textContent,
                "timeStamp" : trElements[i].children[8].textContent
            }
            timeCollection.push(obj);
        }
    }

    function getNumber() {
        timeCollection.forEach(function findRecent(element) {
            var timeStamp = moment(element["timeStamp"], "MMM. D, YYYY, h:m A");
            var mostRecentMoment = moment(mostRecent["timeStamp"], "MMM. D, YYYY, h:m A");
            if (moment(timeStamp).isAfter(mostRecentMoment)) { mostRecent = element; }
        });

        console.log(mostRecent);
    }

    function refresh() {
        getElements();
        getNumber();
    }

    return {
        mostRecent : mostRecent,
        refresh: refresh
    }
}();

elements.refresh();

最佳答案

您正在执行此操作:

var foo = { bar: 1, baz: 2 };
var tar = foo;
foo = { poo: 3, par: 4 };

tar
// <- { bar: 1, baz: 2 }


有效地失去了参考。

您可以这样做:

var foo = { bar: 1, baz: 2 };
var thing = {
    get tar () { return foo; }
};
foo = { poo: 3, par: 4 };

thing.tar;
// <- { poo: 3, par: 4 }


但是,使用吸气剂会使代码复杂化。您可能更喜欢简单地保留引用“更高级别”。

var thing = {
    foo: { bar: 1, baz: 2 }
};
// just return thing
thing.foo = { poo: 3, par: 4 };

// as long as you use the reference to thing, foo will always be up to date
thing.foo;
// <- { poo: 3, par: 4 }

10-07 18:15