且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

将所有JavaScript变量保存在页面上

更新时间:2023-12-03 09:15:46

排序.如果您关心的变量都是全局变量,并且不依赖于任何非全局数据,则可以查看以下问题:

Sort of. If the variables you care about are all global, and don't depend on any non global data, you can check out this question: Fetching all (javascript) global variables in a page (Thanks Stegrex)

但这还不是全部.在JS中,大量数据保留在隐藏范围内.这有两个问题:

But that's not the whole story. In JS lots of data is persisted in hidden scopes. This has 2 problems:

  1. 可能无法从全局范围访问对象.
  2. 函数可能取决于创建它们的作用域中的数据,但是不能从全局作用域中访问.

例如:

var globalThing = 'global';
var makeCounter = function() {
  var count = 0;
  return {
    increment: function() { count++; },
    getCount:  function() { return count; }
  }
}
var counter = makeCounter();
counter.increment();
alert(counter.getCount());

此代码的状态现在无法按字面意义保存和重新构成. count是一个闭包,在全局范围内是隐藏的和不可访问的.如果没有更智能的方法来检查和保存对象的内部状态,则无法保留此结构.

The state of this code is now impossible to literally save and reconstitute. count is in a closure, hidden and inaccessible from the global scope. Without a more intelligent way to inspect and save the internal state of your objects, you can't preserve this structure.

因此,也许这不是您要采用的方法.我敢打赌,有一种更清洁的方式来完成您想要的事情.因此,问题就变成了:您为什么需要这个?而你想做什么?

So perhaps this isn't the approach you want to take. I'd bet good money there is a far cleaner way to do what you want. So the question becomes: why do you need this? And what are you trying to do?

我强烈建议您只保存所需的数据,不要试图强行保存整个宇宙.

I'd strongly suggest that you explicitly save just the data you need, and do not try to brute force save the entire universe.

在您的情况下,这很简单:

In your case, that would be simply:

function saveOnlyImportantVaiables() {
  localStorage.theName = theName;
  localStorage.currentTime = currentTime;
}