我创建了一个简单的“要求”机制 (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'
最佳答案
问题是 V8 不允许一个 Context 访问另一个 Context 的全局变量。因此,logger.logThis(this) 没有打印任何内容。
通过在新上下文中设置安全 token 解决了这个问题:
moduleContext->SetSecurityToken(context->GetSecurityToken());
其中 context 是“主”上下文,moduleContext 是包含的脚本在其中运行的新上下文。
关于javascript - v8 无法从在新上下文中编译的脚本访问属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6390705/