Reputation: 295
I am working on a javascript file with javascript functions
that are not inside a closure.
Obviously the function is callable by the console.
I know that adding a closure is best practice. But while tinkering i found that if I add in my file
window.myFunction = {}
the function becomes unavailable through the console. Is this safe ?
Upvotes: 1
Views: 1611
Reputation: 40394
All global variables/functions in Javascript (Browser) are a property of the window object:
var x = "foo";
console.log(window.x); //foo
It's not best practice to pollute the global scope, but it isn't "unsafe" if you control which scripts your page uses. (Although I don't recommend using global variables)
If you do need to have a global variable, consider using a name that you know other script won't use:
(function(window, undefined){
var privateVar = 5;
window.mySite = {
foo: "bar",
func: function(){
return "foo";
}
};
})(window);
console.log(window.mySite.func()); //"foo"
console.log(privateVar) //undefined
Now outside of the IIFE (Immediately-Invoked Function Expression) you can use window.mySite
or just mySite
, while privateVar
won't be accessible.
More info on the window object here
Upvotes: 2