Jint是一个适用于.NET的JavaScript解释器,支持.NET Standard 2.0和.NET 4.6.2(及更高版本)目标,可以在任何现代.NET平台上运行。
Jint的一些用户包括 RavenDB、 EventStore、 OrchardCore、 ELSA Workflows、 docfx、 JavaScript Engine Switcher 等等。
for...of
Array.prototype.includes
await
、async
**
Object.values
、Object.entries
和Object.getOwnPropertyDescriptors
Promise.prototype.finally
...identifier
)Array.prototype.flat
、Array.prototype.flatMap
String.prototype.trimStart
、String.prototype.trimEnd
Object.fromEntries
Symbol.description
BigInt
export * as ns from
for-in
增强globalThis
对象import
import.meta
??
)Promise.allSettled
String.prototype.matchAll
&&=
||=
??=
)1_000
)AggregateError
Promise.any
String.prototype.replaceAll
WeakRef
FinalizationRegistry
.at()
Object.prototype.hasOwnProperty
(Object.hasOwn
)ArrayBuffer.prototype.resize
和ArrayBuffer.prototype.transfer
Atomics.waitAsync
String.prototype.ensureWellFormed
和String.prototype.isWellFormed
Object.groupBy
和Map.groupBy
Promise.withResolvers
/v
Promise.try
intersection
、union
、difference
、symmetricDifference
、isSubsetOf
、isSupersetOf
、isDisjointFrom
)Script
或Module
实例,而不是内容字符串您可以查看引擎比较结果,请记住每个用例都不同,基准测试可能无法反映您的实际使用情况。
加入Gitter聊天,或在stackoverflow上使用jint
标签提问。
这里有一个简短的视频,展示了Jint的工作原理和一些示例用法
https://docs.microsoft.com/shows/code-conversations/sebastien-ros-on-jint-javascript-interpreter-net
引擎实例不是线程安全的,不应同时从多个线程访问它们。
这个例子定义了一个名为log
的新值,指向Console.WriteLine
,然后运行一个调用log('Hello World!')
的脚本。
var engine = new Engine() .SetValue("log", new Action<object>(Console.WriteLine)); engine.Execute(@" function hello() { log('Hello World'); }; hello(); ");
在这里,变量x
被设置为3
,并在JavaScript中计算x * x
。结果直接返回给.NET,在这种情况下作为double
值9
。
var square = new Engine() .SetValue("x", 3) // 定义一个新变量 .Evaluate("x * x") // 计算一个语句 .ToObject(); // 将值转换为.NET对象
您还可以直接传递POCO或匿名对 象,并从JavaScript中使用它们。例如,在这个例子中,一个新的Person
实例从JavaScript中被操作。
var p = new Person { Name = "Mickey Mouse" }; var engine = new Engine() .SetValue("p", p) .Execute("p.Name = 'Minnie'"); Assert.AreEqual("Minnie", p.Name);
您可以调用JavaScript函数引用
var result = new Engine() .Execute("function add(a, b) { return a + b; }") .Invoke("add",1, 2); // -> 3
或直接通过名称调用
var engine = new Engine() .Execute("function add(a, b) { return a + b; }"); engine.Invoke("add", 1, 2); // -> 3
您可以通过配置引擎实例来允许引擎访问任何.NET类,如下所示:
var engine = new Engine(cfg => cfg.AllowClr());
然后,您可以 将System
命名空间作为全局值访问。以下是在命令行实用程序上下文中使用它的方式:
jint> var file = new System.IO.StreamWriter('log.txt'); jint> file.WriteLine('Hello World !'); jint> file.Dispose();
甚至可以为常用的.NET方法创建快捷方式
jint> var log = System.Console.WriteLine; jint> log('Hello World !'); => "Hello World !"
当允许CLR时,您可以选择性地传递自定义程序集以加载类型。
var engine = new Engine(cfg => cfg .AllowClr(typeof(Bar).Assembly) );
然后,要以与System
相同的方式分配本地命名空间,请使用importNamespace
jint> var Foo = importNamespace('Foo'); jint> var bar = new Foo.Bar(); jint> log(bar.ToString());
添加特定CLR类型引用可以这样做
engine.SetValue("TheType", TypeReference.CreateTypeReference<TheType>(engine));
并以这种方式使用
jint> var o = new TheType();
也支持泛型类型。以下是如何声明、实例化和使用List<string>