Jurassic [C# .Net Unity JavaScript运行时] 二.高级用法

从JavaScript调用单个.NET方法

您可以使用SetGlobalFunctionAPIJavaScript调用任何.NET 。例如:

var engine = new Jurassic.ScriptEngine();
engine.SetGlobalFunction("test", new Func<int, int, int>((a, b) => a + b));
Console.WriteLine(engine.Evaluate<int>("test(5, 6)"));

此代码将向控制台输出"11"

请注意以下几点:

  • 必须全部支持委托参数类型和返回类型。
  • 在提供的委托中引发的异常无法在JavaScript中捕获(除非它是JavaScriptException)。
  • 由于安全限制,以上示例在Silverlight中不起作用。要解决此问题,请将委托传递给公共方法。

从.NET调用JavaScript函数

您也可以从.NET调用JavaScript函数。

var engine = new Jurassic.ScriptEngine();
engine.Evaluate("function test(a, b) { return a + b }");
Console.WriteLine(engine.CallGlobalFunction<int>("test", 5, 6));

此代码将"11"输出到控制台。

将.NET类暴露给JavaScript

Building a property bag class

首先,让我们创建一个包含几个属性的类。

using Jurassic;
using Jurassic.Library;

public class AppInfo : ObjectInstance
{
    public AppInfo(ScriptEngine engine)
        : base(engine)
    {
        // Read-write property (name).
        //类索引器可用于创建读写属性。
        this["name"] = "Test Application";

        // Read-only property (version).
        //`DefineProperty`可用于创建只读属性
        this.DefineProperty("version", new PropertyDescriptor(5, PropertyAttributes.Sealed), true);
    }
}

在此示例中,有几件事要注意:

  • 暴露给JavaScript的类需要继承Jurassic.Library.ObjectInstance
  • ScriptEngine传递给基类构造函数意味着该对象将没有原型。因此,常规功能(hasOwnProperty,toString)将不可用。
  • 类索引器可用于创建读写属性。
  • DefineProperty可用于创建只读属性。

这是有关如何创建和使用新类的示例:

var engine = new Jurassic.ScriptEngine();
engine.SetGlobalValue("appInfo", new AppInfo(engine));
Console.WriteLine(engine.Evaluate<string>("appInfo.name + ' ' + appInfo.version"));

Building a class with static functions

下一步是使用静态函数创建一个类,类似于内置Math对象的工作方式。例如,假设您要使用log10函数创建一个新的Math2对象:

using Jurassic;
using Jurassic.Library;

public class Math2 : ObjectInstance
{
    public Math2(ScriptEngine engine)
        : base(engine)
    {
        this.PopulateFunctions();
    }

    [JSFunction(Name = "log10")]
    public static double Log10(double num)
    {
        return Math.Log10(num);
    }
}

请注意以下几点:

  • PopulateFunctions 在类中搜索[JSFunction]属性,并为找到的每个属性创建一个函数。
  • [JSFunction]属性允许JavaScript函数名称与.NET方法名称不同。
  • 参数类型和返回类型必须在[支持的类型|支持的类型]列表中。
  • 使用[JSProperty]属性装饰属性可将属性作为访问者公开给脚本。因此,您可以在CLR中编写带有支持者的属性,或在CLR代码中设置只读属性。

这是有关如何创建和使用新类的示例:

var engine = new Jurassic.ScriptEngine();
engine.SetGlobalValue("math2", new Math2(engine));
Console.WriteLine(engine.Evaluate<double>("math2.log10(1000)"));

Building an instance class

可以实例化的对象(例如内置的Number,String,Array和RegExp对象)需要两个.NET类,一个用于构造函数,一个用于实例。例如,让我们制作一个与.NET Random类类似的JavaScript对象(带有种子,因为JavaScript不支持该对象):

using Jurassic;
using Jurassic.Library;

public class RandomConstructor : ClrFunction
{
    public RandomConstructor(ScriptEngine engine)
        : base(engine.Function.InstancePrototype, "Random", new RandomInstance(engine.Object.InstancePrototype))
    {
    }

    [JSConstructorFunction]
    public RandomInstance Construct(int seed)
    {
        return new RandomInstance(this.InstancePrototype, seed);
    }
}

public class RandomInstance : ObjectInstance
{
    private Random random;

    public RandomInstance(ObjectInstance prototype)
        : base(prototype)
    {
        this.PopulateFunctions();
        this.random = new Random(0);
    }

    public RandomInstance(ObjectInstance prototype, int seed)
        : base(prototype)
    {
        this.random = new Random(seed);
    }

    [JSFunction(Name = "nextDouble")]
    public double NextDouble()
    {
        return this.random.NextDouble();
    }
}

请注意以下几点:

  • 您需要两个类-一个是构造函数(即调用new的函数对象),另一个是实例对象。
  • ClrFunction基类需要三个参数:函数对象的原型,函数的名称和使用该函数创建的任何实例的原型。
  • [JSConstructorFunction]属性标记使用新运算符时调用的方法。您也可以使用[JSCallFunction]标记直接调用该函数时所调用的方法。
  • RandomInstance类具有两个构造函数-一个用于初始化原型,一个用于初始化所有其他实例。 PopulateFunctions只能从原型对象中调用。

这是有关如何创建和使用新类的示例:

var engine = new Jurassic.ScriptEngine();
engine.SetGlobalValue("Random", new RandomConstructor(engine));
Console.WriteLine(engine.Evaluate<double>("var rand = new Random(1000); rand.nextDouble()"));

这将向控制台输出"0.151557459100875"(由于我们使用的是种子,因此每次对nextDouble()的第一次调用都相同。)

这个例子涉及更多,但是它支持所有高级JavaScript概念:

  • rand支持内置的Object函数(hasOwnProperty,toString等)。
  • rand利用原型继承。在这种情况下,您具有以下原型链:random instance (with no properties) -> random prototype (with nextDouble defined) -> object prototype -> null.

从自定义源加载脚本

如果要执行的脚本不在文件中,并且不想将其加载到字符串中,则可以创建一个custom ScriptSource。以下示例显示了如何完成此操作:

/// <summary>
/// Represents a string containing script code.
/// </summary>
public class StringScriptSource : ScriptSource
{
    private string code;

    /// <summary>
    /// Creates a new StringScriptSource instance.
    /// </summary>
    /// <param name="code"> The script code. </param>
    public StringScriptSource(string code)
    {
        if (code == null)
            throw new ArgumentNullException("code");
        this.code = code;
    }

    /// <summary>
    /// Gets the path of the source file (either a path on the file system or a URL).  This
    /// can be <c>null</c> if no path is available.
    /// </summary>
    public override string Path
    {
        get { return null; }
    }

    /// <summary>
    /// Returns a reader that can be used to read the source code for the script.
    /// </summary>
    /// <returns> A reader that can be used to read the source code for the script, positioned
    /// at the start of the source code. </returns>
    /// <remarks> If this method is called multiple times then each reader must return the
    /// same source code. </remarks>
    public override TextReader GetReader()
    {
        return new StringReader(this.code);
    }
}

线程与并发

侏罗纪不是线程安全的。但是,它也不使用任何线程局部或全局状态。因此,只要确保没有一次从多个线程调用任何Jurassic对象,它将起作用。确保这一点的最简单方法是使用多个脚本引擎(每个线程一个是理想的)。由于非原始对象绑定到单个脚本引擎,因此每个脚本引擎都完全相互隔离。这确实使脚本引擎之间难以共享数据。共享数据的一种方法是将其序列化为字符串,然后在线程之间传递(JSON对象可用于序列化JavaScript对象)。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容