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

Community
  • 1
  • 1
Nate Anderson
  • 18,334
  • 18
  • 100
  • 135
  • 2
    `global_var = {'key' : 'value'};` --> `window.global_var`; Works for me in Chrome 47. – Antiga Jan 06 '16 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? – Nate Anderson Jan 06 '16 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? – Medet Tleukabiluly Jan 06 '16 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, http://stackoverflow.com/a/11596399/1175496 and oddly it tells me `window.global_var` is undefined, even though I can reach just `global_var` – Nate Anderson Jan 06 '16 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 – Medet Tleukabiluly Jan 07 '16 at 17:00
  • Yeah, `window.global_object` sounds like a reasonable compromise. Just find it strange that `global_object = ... ` wasn't working. Maybe some strange setting I have. I'm fine if this question is closed as "too user specific/cannot reproduce" or some equivalent reason. – Nate Anderson Jan 08 '16 at 03:57

0 Answers0