How to isolate a function from global variables

I am creating a small coding game. For this game, each player represents a javascript function. The game performs each of these functions several times in a row, and I collect the values ​​returned by the functions. These return values ​​are important to the game. Therefore, if playerFunc is a function passed by the player, my game might do something like this:

var values = [] for(var i = 0; i < 1000; i++){ values.push(playerFunc(i)) } doSomething(values) 

The problem is that I want players to not transfer data from one call to the next. For example, I would not want there to be some way to call the playerFunc function to find out if it has already been called with argument 0. For this, I believe that I need to prevent access to the functions passed by the player to the closures and global variables.

I know that I can get rid of closures by creating each function using the Function constructor, so I think I figured it out. Blocking access to global variables is what I came across.

I can completely isolate every function call by running it in a web worker, but I read that web workers take about 40 ms to set up, and I may have to perform these functions up to 1000 times per second, so to slow down.

Is there any other way to prevent the function from accessing global variables, or to somehow reset the global scope after each function call?

At the moment, this game will only be played with friends, so I don’t worry that the players are doing something evil, but I think they can try to cheat.

+7
javascript
source share
1 answer

You can try something like this:

 var createFunction = function(fnBody) { var f = new Function('obj', 'window', 'document', '"use strict";' + fnBody); return f.bind({}, {}, {}, {}); } 

Any access to a window or document will use parameters instead of global variables. You can add global variables to restrict access. Using "use strict"; you will terminate the available function from accessing the global scope using undefined variables.

 var createFunction = function(fnBody) { var f = new Function('obj', 'window', 'document', '"use strict";' + fnBody); return f.bind({}, {}, {}, {}); } createFunction('window.hello = "test"')(); console.log(window.test); //undefined createFunction('hello = "test";')(); //throws error console.log(hello); 

This causes an error.

+1
source share

All Articles