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:
- 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.
- Cookies. Cookies can store 4KiB of data, but some users disable them.
window.name
. You can store up to 2MiB of data inwindow.name
. Here is a library that focuses on storing data inwindow.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.
精彩评论