0

This is strange... in function getNumber() the variable mostRecent is not accessing the outer variable var mostRecent.

I see in console that console.log(mostRecent) is showing mostRecent is updated, but when I do elements.mostRecent it still shows the default value.

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();

2 Answers 2

4

The property mostRecent will not automatically update when the internal variable mostRecent changes. Make it a function instead to get the latest version of the internal variable:

return {
    getMostRecent: function () { 
        return mostRecent; 
    },
    refresh: refresh
};
Sign up to request clarification or add additional context in comments.

1 Comment

Originally, in return { mostRecent : mostRecent }, was the { mostRecent : a variable holding a copy of the var mostRecent contents rather than a reference to the memory location?
2

You are doing this:

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

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

Effectively losing the reference.

You could do:

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

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

Using getters can complicate your code, though. You may prefer to simply keep the reference "a level above".

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 }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.