1

I am working on an application that require a js variable to share between 2 or 3 scripts only. Now I am using a global variable to share. Is it possible to restrict the sharing of a global variable between only 2 script files?

Bergi
  • 630,263
  • 148
  • 957
  • 1,375
Imran Qadir Baksh - Baloch
  • 32,612
  • 68
  • 179
  • 322
  • 3
    No. Either it is global or not. What do you expect? – Bergi Jan 20 '13 at 09:14
  • 2
    no, there is no kind of access modification in js, the variable is either public or wrapped in a closure – philipp Jan 20 '13 at 09:14
  • This may help you http://stackoverflow.com/questions/944273/how-to-declare-a-global-variable-in-a-js-file – Hary Jan 20 '13 at 09:15
  • @Bergi, Actually, I don't want the client apps being able to use this variable because it was only intended to share between scripts. – Imran Qadir Baksh - Baloch Jan 20 '13 at 09:16
  • @user960567: And how would you distinguish between "client apps" and "scripts"? – Bergi Jan 20 '13 at 09:18
  • Actually client apps are native android, Iphone and Windows Phone – Imran Qadir Baksh - Baloch Jan 20 '13 at 09:21
  • Huh? Please tell us more about your environment and what you are actually trying to do. – Bergi Jan 20 '13 at 10:14
  • @Bergi, I have lot of script files which somehow needed to talk with each other. it works great. But I don't want the client Iphone which contains (Web UIWebView) and Android which contains WebView, able to call any function. – Imran Qadir Baksh - Baloch Jan 20 '13 at 12:18
  • @user960567: So you are displaying a website in a `UIWebView`, which contains some external scripts. Now which globals do you have (in the website) that should be access-limited? – Bergi Jan 20 '13 at 13:24
  • @Bergi, I don't want to go in detail. Because it's a big project with lot of scripts that are dynamically loaded when required. My question is simple. – Imran Qadir Baksh - Baloch Jan 20 '13 at 15:30
  • @user960567: The answer to your simple question is *No*, as stated in my first comment. So I asked what you actually wanted to do, and why you thought you would need to restrict access to global variables. – Bergi Jan 20 '13 at 15:39

2 Answers2

1

No, this is not possible. YOu may use namespace instead. eg

var a={};
a.b={};
a.b.foo= 'something';
chendu
  • 684
  • 9
  • 21
1

I agree with Ravi, take a look at namespacing which may give you a bit more flexibility, check out this post Addy Osmani which provides excellent overview of nested namespaces

http://addyosmani.com/blog/essential-js-namespacing/

bhooper27
  • 11
  • 1