2014-01-07 66 views
0

这很奇怪...在function getNumber()变量mostRecent没有访问外部变量var mostRecentJavascript模块在功能上是可变的,没有访问外部变量

我在控制台中看到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(); 

回答

2

你这样做:

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 } 
4

属性mostRecent不会自动更新的内部变量mostRecent变化时。使它成为一个功能,而不是获取最新版本的内部变量:

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

最初,换来{mostRecent:mostRecent},是{mostRecent:一个变量保存的VAR mostRecent内容的副本,而不是引用到内存位置? – dman