开发者

Javascript global namespace and dynamic property question

Say I want to have a global object which can be visible and accessible across pages(??)

// core.js
var MyLib = {}; // global Object cointainer
MyLib.value = 1;

If I define this way, then I can have access to MyLib.value in other places as long as I load the core.js.

However, if I want to add new property to object MyLib in somewhere else, say:

//extra.js
MyLib.otherVal = 2;

Then I try to access MyLib.otherVal from a different place, it is not available. I probably have some fundamental 开发者_运维技巧misunderstanding on how this suppose to work. I hope someone can enlighten me.

After reading the comments, I realized the scope I want is indeed across pages. Is that even possible?

thanks

Oliver


If you want to carry data across pages, there are really three major methods:

  1. LocalStorage. See this page for a fairly thorough explanation of the concept, how to use it, and so forth. Here is a library dealing with JavaScript storage.
  2. Cookies. Cookies can store 4KiB of data, but some users disable them.
  3. window.name. You can store up to 2MiB of data in window.name. Here is a library that focuses on storing data in window.name; it seems fairly well-written.

You could potentially write an app to take advantage of all three of these techniques, starting with LocalStorage and falling back to window.name if all else fails.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜