0

Within Javascript, you can create and call a function as such:

function test_1(){ console.log(1); }
window['test_1']() // --> 1

However, my current code is scoped:

(function(){
    function test_1(){ console.log(1); }
    window['test_1']() // --> not a function 
})();

...making any created functions not be bound to the window-level, but to the specific scope level.

How can I create a function within a scope, and then dynamically* call that function?

*By dynamically I mean that I can dynamically alter the string with a variable, such as window['test_'+index]().

Davy
  • 691
  • 1
  • 7
  • 18
  • 1
    `window.test_1 = function(){}` – Rayon Apr 24 '17 at 13:08
  • Your issues is becuase of global vs local scope. – epascarello Apr 24 '17 at 13:08
  • The entire point of scoping functions like shown in your second code snippet is to limit the scope in which they are available. If you want them to be globally available, just don't scope them. If you _don't_ want them to be globally available, just access them from the correct scope. The combination you ask for is impossible, and does not really make sense. – ArneHugo Apr 24 '17 at 13:20
  • Thanks people, although I'd like to make it clear that this wasn't a scoping 'error', but something that's not possible. @epascarello is correct that it's a duplicate, the second question helped - However, with all the terms I used to search for it I couldn't find the question myself. As an answer, I went with making the function part of an object and referencing that. Thanks! – Davy Apr 24 '17 at 13:29

2 Answers2

1

Global variables become properties of the window object.

Non-global variables do not automatically become properties of any object.

You can't do this.


Consider making the function a property of an object explicitly instead.

(function(){
    var functions = {};
    functions.test_1 = function test_1(){ console.log(1); };
    functions['test_1']();
})();
Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
-1

To call the scoped function from within the scope you just call it by name (do not use window):

(function(){
    function test_1(){ console.log(1); }
    test_1();
})();

To call the scoped function from outside the scope you need to export it into the calling scope:

var scope = (function(){
    function test_1(){ console.log(1); }
    return {
        test_1: test_1
    };
})();

scope.test_1();
Joe Green
  • 1,745
  • 1
  • 12
  • 17