簡體   English   中英

當被調用函數本身在上下文中時,如何避免nodejs vm腳本函數調用丟失上下文?

[英]How do I avoid nodejs vm script function call losing context when called function is itself in the context?

問題:我正在使用nodejs vm運行提供的腳本(可信源,但不在我的控件中)。 提供的腳本必須在收到的上下文中回調我提供的功能。

腳本內部的功能按預期工作。 但是,當調用上下文中提供的函數時,該函數不再具有提供給被調用腳本的上下文中的任何變量。 這個簡短的程序演示了該問題:

var vm = require('vm');
var sandbox={console:console, myfn:function() {
        console.log("MYFN");
        console.log("MYFN: a="+a);
}, a:42};
var ctx = new vm.createContext(sandbox);
vm.runInContext("function okfn() { console.log('OKFN'); console.log('OKFN: a='+a); } console.log('TEST'); console.log('TEST: a='+a);okfn(); myfn();", ctx, {filename:"TEST"});

當它運行時,我希望看到以下輸出:

TEST
TEST: a=42
OKFN
OKFN: a=42
MYFN
MYFN: a=42

但是,相反,myfn()中的最后一個console.log會產生ReferenceError:未定義

當腳本調用上下文本身提供的函數時,是否有辦法保留通過runInContext()傳遞給腳本的上下文?

函數綁定到定義它們的全局范圍。 由於myfn是在主腳本文件中定義的,因此它將使用該文件的全局變量。 為了將該功能綁定到另一個全局上下文,必須在該上下文中重新定義/重新執行它:

var vm = require('vm');

function myfn() {
    console.log("MYFN");
    console.log("MYFN: a="+ a);
}


var sandbox={console:console, a:42};
var ctx = new vm.createContext(sandbox);

// Evaluates the source code of myfn in the new context
// This will ensure that myfn uses the global context of 'ctx'
vm.runInContext(myfn.toString(), ctx, {filename: "TEST"});

// Retained in the context
console.log(ctx.myfn);

// Use it
vm.runInContext("function okfn() { console.log('OKFN'); console.log('OKFN: a='+a); } console.log('TEST'); console.log('TEST: a='+a);okfn();  myfn();", ctx, {filename:"TEST"});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM