0

My understanding (Based on experience and posts like this) If my Javascript does this:

global_var = {'key' : 'value'} 

Then I should be able to do this:

console.log(window.global_var) 

Or

console.log(window['global_var']) 

I expect those things to actually log the object to my console {'key':'value'}. In fact both of the latter two statements print undefined

I know I can do this:

window.global_var = {'key' : 'value'} 

But that's not what I want (just humor me)

I've tried this from Javascript files loaded to the page. I've also tried from the Chrome Developer Console, both directly (repeating above), and also using "Store as Global Variable"

=console.log({'key':'value'}) VM1587:1 Object {key: "value"} undefined {I right-click on the Object logged above and choose "save as Global Variable"} temp1 Object {key: "value"} window.temp1 undefined 

I am using Chrome Version 47.0.2526.106 m

6
  • 2
    global_var = {'key' : 'value'}; --> window.global_var; Works for me in Chrome 47. Commented Jan 6, 2016 at 19:41
  • Sorry , it works for me in one Developer tab, but not another. Could there be some setting that the webpage has loaded, or some setting the Chrome tab has set to affect this behavior? Commented Jan 6, 2016 at 19:45
  • This is funny case indeed, as I recall, global_var should be accessible without window object, maybe your magic right click and save does something you don't expect? Why would you even use it? Commented Jan 6, 2016 at 19:52
  • Yeah @Medet -- maybe user error. I appreciate polluting global scope sucks. Currently we're very simplistic. In this case, Script X.js has something Script Y.js needs. We're not advanced enough to define dependencies like AMD and etc. We don't even have a top-level namespace like ourcompany={}, so we could at least populate that. We simply make sure Script X.js is loaded before Script Y.js. But to be safer still I am trying to do this, stackoverflow.com/a/11596399/1175496 and oddly it tells me window.global_var is undefined, even though I can reach just global_var Commented Jan 6, 2016 at 20:32
  • So it basically decision of taste, I would suggest to use window.global_object, though you don't want to follow any conventions, then just write as you want(I mean AMD loaders), I don't think SO can help with this Commented Jan 7, 2016 at 17:00

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.