我正在调试运行在Atom编辑器中的另一个人的包(当前未维护)。此程序包一度使用vm.runInContext定义一个类对象,使用的代码相当于以下代码:
const vm = require('vm')
myClass = vm.runInNewContext('class x {}', {}, 'file')我认为这段代码可以在node.js中运行,但我并不真正了解Atom的javascript环境的所有细节。无论如何,我非常确定它可以在ES6或更高版本中运行。我相信当这个包在2017年4月最后一次更新时,对vm.runInNewContext的调用返回了一个有效的类对象。然而,它目前返回undefined,可能是因为自那以后(可能在2018年6月1日左右)对Atom进行了一些升级。正因为如此,对myClass属性的引用现在失败了,这就是我试图修复的错误。
我相信这里发生的事情是javascript将class x {}代码解释为类声明,而类声明没有值,所以vm.runInNewContext返回undefined。因此,我正在寻找一种优雅的方式来强制此代码返回一个类,而不是undefined。我发现了以下可能性:
// add a reference to the class, which will be returned as the final value
vm.runInNewContext('class x {}; x', {}, 'file')
// use an assignment, which treats this as a class expression,
// then the assignment is returned as the final value
vm.runInNewContext('var x; x = class x {}', {}, 'file')
// note: a simpler version ('var x = class x {}') returns undefined
// wrap the class statement in parentheses, so it is evaluated as
// a class expression instead of a class declaration
vm.runInNewContext('(class x {})', {}, 'file')所有这些工作,但看起来都很笨拙。有没有什么“标准”的方法来强制javascript / ES6把class x {}当作类表达式而不是类声明?
发布于 2018-07-24 04:50:18
此行为不是Node.js vm.runInNewContext所特有的。代码应该被强制评估为表达式。
eval('function foo () {}') === undefined因为它被视为函数声明,而不是函数表达式。出于同样的原因,此行将导致语法错误:
function () {};它不是有效的函数声明,并且未用作表达式。
所以圆括号
vm.runInNewContext('(class x {})', {}, 'file')或逗号运算符
vm.runInNewContext('0, class x {}', {}, 'file')是使计算代码成为表达式的传统方法。
https://stackoverflow.com/questions/51486025
复制相似问题