succeed
succeed

Reputation: 1040

calling a function from its string name on Window object

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
 }();

Upvotes: 0

Views: 452

Answers (1)

Razzi Abuissa
Razzi Abuissa

Reputation: 4112

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.

Upvotes: 1

Related Questions