3

I've created a simple 'require' mechanism (https://gist.github.com/1031869), in which the included script is compiled and run in a new context. However, when I call a function in the included script and pass it this, the included script doesn't see any properties in it.

//required.js - compiled and run in new context
exports.logThis = function(what){
    for (key in what) log(key + ' : ' + what[key]);
}

//main.js
logger = require('required');
this.someProp = {some: 'prop'}
logger.logThis({one: 'two'});   //works, prints 'one : two'
logger.logThis(this); //doesn't work, prints nothing. expected 'some : prop'
logger.logThis(this.someProp); //works, prints 'some : prop'
ildjarn
  • 62,044
  • 9
  • 127
  • 211
Florin
  • 2,891
  • 4
  • 19
  • 26
  • What displays the `logger.logThis(this);` statement if you call it inside the main.js file? – Florian Jun 17 '11 at 22:24
  • logger.logThis(this) called from main.js displays nothing. If I do for (key in this) log(key) in main.js then it displays the properties of this (like the log function and someProp). But if I run the same code in required.js, then nothing is printed. – Florin Jun 18 '11 at 08:18
  • That's strange, maybe file a bug? – Florian Jun 18 '11 at 12:51

1 Answers1

4

The problem was that V8 doesn't allow a Context to access the global variables of another Context. Hence, logger.logThis(this) wasn't printing anything.

This was solved, by setting the security token on the new context:

moduleContext->SetSecurityToken(context->GetSecurityToken());

where context is the 'main' context and moduleContext is the new context in which the included script runs.

Florin
  • 2,891
  • 4
  • 19
  • 26