Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Isolated execution context in JavaScript

I'm trying to execute a piece of code within an empty isolated execution context in JavaScript. In the below sample, I'm trying isolate isolated execution scope. What I want to do is to execute a function in context where no global variables are in.

(function() {
  'use strict';

  var scope = Object.create(null);
  var isolated = function() {
    'use strict';
    console.log(document); // Trying to get undefined
                           // but traces `document`.
  };

  isolated.call(scope);
})();

I thought it was simple to nullify global variables but there are too many!

var isolated = function(window, document, location /* etc */) {
  // ...
};

isolated.call(scope, undefined, undefined, undefined /* etc */);

Is there a better way to do this?

like image 665
Florent Avatar asked Sep 02 '25 10:09

Florent


2 Answers

There is no good way to do this within javascript itself (but see Gareth Hayes answer for another option).

There are a couple of bad ways.

(function() {
  var scope = Object.create(null);
  var obscurer = {};
  for (var key in this) {
     obscurer[key] = undefined;
  }

  with (obscurer) {
    var isolated = function() {
      'use strict';
      console.log(document);
    };
  }

  isolated.call(scope);
})();

Note that you'll actually get an error because console is not defined rather than document, although you can fix this by not blocking 'console' in the obscurer object. You'll probably find that you need a whole bunch more globals than you realised.

You're also only blocking the enumerable properties of window. If you become aware of nonenumerable properties that you want to block too, you'll have to add those to obscurer.

Of course, using with means you can't use strict mode any more as well, and everyone will look down their noses at you..

There are more interesting options available if you are working within node rather than the browser.

like image 97
kybernetikos Avatar answered Sep 05 '25 02:09

kybernetikos


Use my MentalJS parser to isolate the environment. You can then choose which objects/variables it has access to by customizing the code.

http://businessinfo.co.uk/labs/MentalJS/MentalJS.html

http://code.google.com/p/mentaljs/

By default it allows access to document but you can prevent this, customize the environment here http://code.google.com/p/mentaljs/source/browse/trunk/MentalJS/javascript/Mental.js#260 you can then choose if they have access to Math etc.

like image 21
Gareth Heyes ล้้้้้้้้้้้้้้้้ Avatar answered Sep 05 '25 00:09

Gareth Heyes ล้้้้้้้้้้้้้้้้