Reputation: 6551
Iam a new guy in JS and iam doing a mobile project in phonegap, i want to know how to keep a variable in overall page scope, not global variable since it will eat lot of memory which is not acceptable for a mobile developer, i have two or more JS tags in a page as shown,
<script type="text/javascript">
// script one here
</script>
<html> //html block here </html>
<script type="text/javascript">
// script two here
</script>
so i request your valuable suggestion & help. Thanks!
Upvotes: 0
Views: 1197
Reputation: 276326
"Overall Page scope" is global scope.
JavaScript scoping (generally, except for specific esoteric scopes*) works in two ways:
Since you can't share a function over script tags, a global is your only choice.
Consider passing messages to share data instead of a global.
Here is how something like this could be done with message passing:
Script 0:
window.pubsub = (function(){
var subscribers = [];
return {
subscribe:function(user){
subscribers.push(user);
},
publish:function(message,data){
subscribers.forEach(function(elem){
elem.onMessage(data);
});
}
};
})();
Script 1:
(function(pubsub){
var someObject = {}; // to share state
//code here
pubsub.subscribe(someObject);
someObject.onMessage = function(){
//whatever you do when you get a message
};
})(window.pubsub);
Script 2 would be identical, only it would handle messages differently.
This way, you have one global variable (if that's too much, you can even delete window's reference to it after subscribing script 2, which would mean no globals at all)
*technically try/catch and with also introduce scope, but they're very rare and should not be used like this
Upvotes: 2