succeed succeed - 6 months ago 16
Javascript Question

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

Answer

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.