简体   繁体   中英

How to isolate a function from global variables

I'm building a little coding game. For this game, each player submits a javascript function. The game runs each of these functions a number of times in succession, and I collect the values the functions return. These returned values are what's important for the sake of the game. So if playerFunc is a player-submitted function, 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, I want to prevent players from passing data from one invocation to the next. For example, I wouldn't want there to be any way for an invocation of playerFunc to figure out if it had already been called with an argument of 0. To do this, I figure I need to prevent the player-submitted functions from accessing closures and global variables.

I know I can get rid of the closures by creating each function with the Function constructor, so I think I've got that figured out. Blocking access to global variables is what I'm having trouble with.

I can totally isolate each function call by running it in a web worker, but I've read that web workers take around 40ms to setup, and I may need to be running these functions up to 1000 times a second, so that's to slow.

Is there any other way I could prevent a function from accessing global variables, or of somehow resetting the global scope after each function call?

This game will only be played with friends for now, so I'm not worried about the players doing anything malicious, but I do think they might try to cheat.

You could try something like this:

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

Any access to window or document will use the parameters instead of the global variables. You are welcome to add more global variables to restrict access. With "use strict"; , you'll stop the supplied function from accessing the global scope with 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 throws an error.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM