3

我创建了一个简单的“require”机制(https://gist.github.com/1031869),其中包含的脚本被编译并在新的上下文中运行。但是,当我在包含的脚本中调用函数并传递它this时,包含的脚本看不到其中的任何属性。

//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'
4

1 回答 1

4

问题是 V8 不允许 Context 访问另一个 Context 的全局变量。因此, logger.logThis(this) 没有打印任何内容。

通过在新上下文中设置安全令牌解决了这个问题:

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

其中 context 是“主”上下文,moduleContext 是包含的脚本运行的新上下文。

于 2011-06-28T07:43:59.853 回答