0

Why is the test fuction declaration not found in the window object? Thanks

!function(){
   function test(){
    console.log("testing");
   }   
   var check = window["test"]
   console.log(check); //undefined
 }();
1
  • 1
    Because test is not in the window object? You've created a closure, that's kind of the point... Commented May 15, 2016 at 17:26

1 Answer 1

1

Since function test() is local to the scope of the toplevel function expression, it's not bound to window, the global scope. You can refer to it as a local variable:

!function() {
    function test() {
        console.log('testing')
    }
    console.log(test)
}()

Or bind it directly to window for a global variable:

!function() {
    window.test = function test() {
        console.log('testing')
    }
    var check = window['test']
    console.log(check)
}()

You cannot access the local scope as a variable - see this question for more details.

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.