1

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 ?

2
  • 2
    That assigns a new empty object as the value of your function, and so, your function won't be a function any more. You won't be able to call it in the console or anywhere else. Commented Jan 26, 2016 at 20:19
  • In fact what happened to me was I created an instance of the object and then set it to {}, that's why it worked (because later I was calling the instance and not the object itself) Commented Jan 26, 2016 at 21:52

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.