How do I make a global object in JavaScript? This is some example code
function main() {
window.example {
sky:"clear",
money:"green",
dollars:3000
}
}
So why can I not access the object outside the function?
You missed the =
window.example = {
sky:"clear",
money:"green",
dollars:3000
}
In node window is undefined, if you really want to use window as a global variable make sure to declare it as
var window = {}
Not sure why you would do that
Because you're not setting anything.
function main() {
window.example = {
sky:"clear",
money:"green",
dollars:3000
}
}
Not a property of window and Global:
var globalExample = {
sky: 'clear',
money: 'green',
dollars: 3000
}
// don't have to even use `var` with top level variables - It's a good practice anyways though
function main() {
this.example = globalExample;
}
var nm = new main;
nm.example.sky = 'grey';
console.log(globalExample.sky);
Constructor style.