简体   繁体   English

JavaScript模块是函数中的变量,无法访问外部作用域变量

[英]Javascript module is variable in function not accessing the outer scope variable

This is strange... in function getNumber() the variable mostRecent is not accessing the outer variable var mostRecent . 这很奇怪...在function getNumber() ,变量mostRecent没有访问外部变量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. 我在控制台中看到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();

The property mostRecent will not automatically update when the internal variable mostRecent changes. 内部变量mostRecent更改时,属性mostRecent不会自动更新。 Make it a function instead to get the latest version of the internal variable: 使其成为一个函数,以获取内部变量的最新版本:

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

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 }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM